My problem is to replace strings in a text file, with another string. These key strings are in a list called word_list. I've tried the following, nothing seems to work. It prints out the sentence in document.text as it appears, with no replacement:
word_list = {'hi' : 'test', 'how' : 'teddy'}
with open("document.txt") as main:
words = main.read().split()
replaced = []
for y in words:
replacement = word_list.get(y, y)
replaced.append(replacement)
text = ' '.join(word_list.get(y, y) for y in words)
print text
new_main = open("done.txt", 'w')
new_main.write(text)
new_main.close()
Content of document.txt:
hi you, how is he?
Current output is the same as document.txt when it should be:
test you, teddy is he?
Any solutions/ help would be appreciated :)
replacemethodword_listis, despite its name, a dictionary... Also, you completely ignorereplacedwhen you create thetextat the end, preferring instead to use a generator expression.