I need to replace all words in a text document that are of length 4 with a different word.
For example, if a text document contained the phrase "I like to eat very hot soup" the words "like", "very", and "soup" would be replaced with "something"
Then, instead of overwriting the original text document, it needs to create a new one with the changed phrase.
Here is what I have so far:
def replacement(): o = open("file.txt","a") #file.txt will be the file containing the changed phrasefor line in open("y.txt"): #y.txt is the original fileline = line.replace("????","something") #see belowo.write(line + "\n")o.close()
I've tried changing "????" to something like
(str(len(line) == 4)
but that didn't work
First lets make a function that returns something
if it's given a word of length 4 and the word it was given otherwise:
def maybe_replace(word, length=4):if len(word) == length:return 'something'else:return word
Now lets walk through your for loop. In each iteration you have a line of your original file. Lets split that into words. Python gives us the split
function that we can use:
split_line = line.split()
The default is to split on whitespace, which is exactly what we want. There's more documentation if you want it.
Now we want to get the list of calling our maybe_replace
function on every word:
new_split_line = [maybe_replace(word) for word in split_line]
Now we can join these back up together using the join
method:
new_line = ' '.join(new_split_line)
And write it back to our file:
o.write(new_line + '\n')
So our final function will be:
def replacement(): o = open("file.txt","a") #file.txt will be the file containing the changed phrasefor line in open("y.txt"): #y.txt is the original filesplit_line = line.split()new_split_line = [maybe_replace(word) for word in split_line]new_line = ' '.join(new_split_line)o.write(new_line + '\n')o.close()