在文件python中查找和替换多个单词

2022-01-20 00:00:00 python find replace

问题描述

我从 这里.

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()

相关文章