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 phrase
for line in open("y.txt"): #y.txt is the original file
line = line.replace("????","something") #see below
o.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
somethingif it’s given a word of length 4 and the word it was given otherwise: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
splitfunction that we can use: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_replacefunction on every word:Now we can join these back up together using the
joinmethod:And write it back to our file:
So our final function will be: