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

2024-04-23 12:03:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我从here中获取了示例代码。

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)替换。

提前谢谢!


Tags: texttxt示例newcloseherelineopen
3条回答
def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

我们的方法replace_all(),接受两个参数。第一个是文本,它是替换发生的字符串或文件(它是文本)。第二个是dic,它是一个字典,我们的单词或字符将被替换为关键字,替换的单词或字符将被替换为关键字的值。如果只替换一个单词或字符,则此词典只能有一个key:value对;如果同时替换多个单词或字符,则此词典可以有多个key:value对。

Search and Replace multiple words or characters with Python

很容易使用重新模块

import re
s = "old_text1 old_text2"
s1 = re.sub("old_text" , "new_text" , s)

output

'new_text1 new_text2'

re.sub用新文本替换旧文本 回复子文档https://docs.python.org/3.7/library/re.html#re.sub

您可以迭代检查单词,并使用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()

相关问题 更多 >