我的问题是用另一个字符串替换文本文件中的字符串。这些关键字符串位于名为word_list的列表中。我试过以下,似乎没有任何工作。它打印出document.text句子,因为它的出现,有没有替代:文档.txt的Python替换文本文件中的字符串与列表中的值
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()
内容:
hi you, how is he?
电流输出是一样的文档.txt当它应该是:
test you, teddy is he?
任何解决方案/帮助将不胜感激:)
你为什么要经历这一切时,你可以使用'replace'方法 – The6thSense
'word_list'尽管有它的名字,但是它是一个字典......另外,当你在最后创建'text'时,你完全忽略'replace',宁愿使用生成器表达式。 – jonrsharpe
和你的代码适合我吗? – The6thSense