【问题标题】:How to substitute several regex in Python? [duplicate]如何在 Python 中替换几个正则表达式? [复制]
【发布时间】: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 个子,然后把它写回来。这是最干净的方式。很少有正则表达式不适用于跨行...

标签: python regex file


【解决方案1】:

我认为最好将所有正则表达式应用于字符串,一次一个,然后再将其写入文件。也许是这样的?

for line in file:
    out = re.sub('patternToChange', 'patternToWrite', line)
    out2 = re.sub('patternToChange2', 'patternToWrite2', out)
    output.write(out2)

上面的代码对我来说很好用 - try it here 如果你愿意的话。另外,完成后请务必.close()您的文件,否则输出可能不会显示在其中。

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 2012-02-16
    • 2016-11-20
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2017-12-20
    相关资源
    最近更新 更多