【发布时间】:2018-01-15 19:29:25
【问题描述】:
我想用正则表达式替换文件中的多个模式。 到目前为止,这是我的(工作)代码:
import re
with open('test.txt', "r") as fp:
text = fp.read()
result = re.sub(r'pattern', 'replacement', str)
result2 = re.sub(r'anotherpattern', 'anotherreplacement2', result)
...
with open('results.txt', 'w') as fp:
fp.write(result_x)
这行得通。但是在每个新行中手动增加变量名称似乎是不优雅的。我怎样才能更好地增加它们?我认为它必须是一个for循环。但是怎么做呢?
【问题讨论】: