Lohith Kumar February 2016

How to automatically change a particular word while writing to a file in python?

Say a method returns me a long list of lines which I am writing to file. Now on fly is there any way I can change the word "Bread" to "Breakfast", assuming word "Bread" actually exists in several places of my file that is being generated.

Thanks.

I have assigned the sys.stdout to file object, that way all my console print goes to file. So on fly hack would be great.

Answers


zondo February 2016

Assuming that it is the list that you want to be changed rather than the file, and assuming that the list is called lines:

lines = [line.replace("Bread", "Breakfast") for line in lines]


Lindsay Ward February 2016

You can use the replace string method, like:

text.replace('Bread', 'Breakfast')

Note that this doesn't check if it is a 'word', so it would also change 'Bready' to 'Breakfasty'.


Brendan Abel February 2016

You could use regular expressions.

import re

word = 'Bread'
rword = 'Breakfast'
line = 'This is a piece of Bread'
line = re.sub(r'\b{0}\b'.format(re.escape(word)), rword, line)
# 'This is a piece of Breakfast'

The advantage of using regular expressions is that it can detect word boundaries (ie. the \b). This prevents it from replacing words that contain your word (ie. Breadth).

You could do this line by line, or replace the word in the whole document at once.


Andrew Mayes February 2016

str.replace('bread', 'breakfast) where bread is being replaced by breakfast.

Post Status

Asked in February 2016
Viewed 2,336 times
Voted 9
Answered 4 times

Search




Leave an answer