在文件python中查找并替换多个单词 [英] find and replace multiple words in a file python
本文介绍了在文件python中查找并替换多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从此处.
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()
但是我不知道如何用相应的新词替换多个词.在此示例中,如果我想查找诸如(old_text1,old_text2,old_text3,old_text4)
之类的词并将其替换为相应的新词(new_text1,new_text2,new_text3,new_text4)
.
But I am not able to figure out how to replace multiple words with respective new words. In this example if I want to find some words like (old_text1,old_text2,old_text3,old_text4)
and replace by its respective new words (new_text1,new_text2,new_text3,new_text4)
.
提前谢谢!
推荐答案
您可以迭代检查字词,并使用zip
替换字词,然后替换.
You can iterate over your check words and toReplace words using zip
and then replace.
例如:
checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()
这篇关于在文件python中查找并替换多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文