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

bik*_*ser 2 python replace find

我从这里获取示例代码。

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()
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何用各自的新词替换多个词。在这个例子中,如果我想找到一些喜欢的单词,(old_text1,old_text2,old_text3,old_text4)并用它们各自的新单词替换(new_text1,new_text2,new_text3,new_text4)

提前致谢!

Rak*_*esh 6

您可以遍历检查字词,并使用zip替换到替换词。

例如:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这会逐行处理文件,因此对于大文件来说内存效率可能非常高。但它确实有缺点,即无法替换跨多行的单词,就像简单使用“sed”一样。 (2认同)