[英]find and replace multiple words in a file 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)
。
提前致谢!
您可以遍历您的检查词并使用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()
很容易使用 re 模块
import re
s = "old_text1 old_text2"
s1 = re.sub("old_text" , "new_text" , s)
输出
'新文本1新文本2'
re.sub用新文本替换旧文本 re.sub doc https://docs.python.org/3.7/library/re.html#re.sub
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
我们的方法 replace_all() 采用 2 个参数。 第一个,文本,是替换将发生的字符串或文件(它是文本)。 第二个是 dic,是一个字典,其中我们要替换的单词或字符作为键,替换的单词或字符作为该键的值。 如果您只想替换一个单词或字符,此字典可以只有一个键:值对,如果您想一次替换多个单词或字符,则可以有多个键:值。
我了解到这个脚本运行得非常好,而且比我过去使用的脚本要快得多。
import re
def word_replace(text, replace_dict):
rc = re.compile(r"[A-Za-z_]\w*")
def translate(match):
word = match.group(0).lower()
print(word)
return replace_dict.get(word, word)
return rc.sub(translate, text)
old_text = open('YOUR_FILE').read()
replace_dict = {
"old_word1" : 'new_word1',
"old_word2" : 'new_word2',
"old_word3" : 'new_word3',
"old_word4" : 'new_word4',
"old_word5" : 'new_word5'
} # {"words_to_find" : 'word_to_replace'}
output = word_replace(old_text, replace_dict)
f = open("YOUR_FILE", 'w') #what file you want to write to
f.write(output) #write to the file
print(output) #check that it worked in the console
您可以使用正则表达式模块 ( re ) 中的sub替换文本或文件的内容:
def replace_content(dict_replace, target):
"""Based on dict, replaces key with the value on the target."""
for check, replacer in list(dict_replace.items()):
target = sub(check, replacer, target)
return target
或者只是使用不需要from re import sub的str.replace :
def replace_content(dict_replace, target):
"""Based on dict, replaces key with the value on the target."""
for check, replacer in list(dict_replace.items()):
target = target.replace(check, replacer)
return target
这是完整的实现:
from re import sub
from os.path import abspath, realpath, join, dirname
file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()
new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')
def replace_content(dict_replace, target):
"""Based on dict, replaces key with the value on the target."""
for check, replacer in list(dict_replace.items()):
target = sub(check, replacer, target)
# target = target.replace(check, replacer)
return target
# check : replacer
dict_replace = {
'ipsum': 'XXXXXXX',
'amet,': '***********',
'dolor': '$$$$$'
}
new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()
# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet
print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.