【发布时间】:2020-01-03 21:23:17
【问题描述】:
我想循环 .txt 文件中的每一行,然后使用 Python 中的 re.sub 方法来更改某些内容,如果此行中有特定的模式匹配。
但是我怎样才能为同一个文件中的两个不同模式做到这一点呢?
例如,这是我的代码:
file = open(path, 'r')
output = open(temporary_path, 'w')
for line in file:
out = re.sub("patternToChange", "patternToWrite", line) #Here I would like to also do the same trick with "patternToChange2 and patternToWrite2 also in the same file
output .write(out)
你有什么想法吗?
【问题讨论】:
-
您能否提供一个非常基本的输入和预期输出示例?我不太明白这个想法。
-
您能否提供文件中的一些示例行并描述您希望查找的内容和希望替换的内容?从纯粹的角度来看,您当前的代码将从字面上找到
patternToChange并将其替换为patternToWrite。 -
您不能再次运行
re.sub,而是将out作为输入,并使用您的新模式吗?如果您将结果保存回out,则无需进行任何其他更改。 -
python 语法是否允许
re.sub(...).sub(...)在一行中?如果不是,斯科特的想法是正确的,你会在哪里做out = re.sub(pattern1, write1, line)然后out = re.sub(pattern2, write2, out) -
你为什么不把整个文件读成一个字符串,在上面做 2 个子,然后把它写回来。这是最干净的方式。很少有正则表达式不适用于跨行...