【发布时间】:2017-08-15 11:20:04
【问题描述】:
我有两个文本文件:text1 和 text2。
文本1:
(test1)
(test2)
(g)
(test3)
(test4)
(test5)
文本2:
(test5)
(testa)
(testb)
(testc)
(testd)
(teste)
我有以下代码:
import re
pattern = re.compile(r"(\((?!test2:|g}|test4)[\w+ :]+\))")
with open("text2.txt", "r") as f:
words = pattern.findall(f.read())
with open("text1.txt", "r+") as f:
content = pattern.sub(lambda x: words.pop(0) if words else x.group(), f.read())
f.seek(0)
f.write(content)
f.truncate()
这段代码的作用是,通过使用正则表达式,将test1.txt中括号内的单词依次更改为test2.txt中括号内的单词,“test2”除外, “test4”和字母“g”。但是,我想再做一个例外:例如,如果(test5)出现在两个文件中,即使它在不同的行中,它也不会被re选中,因此不会被替换;像这样离开 text1.txt:
(testa)
(test2)
(g)
(testb)
(test4)
(test5)
我的问题是:我应该怎么做?我应该改变我的程序的逻辑吗?还是我应该只更改 RE?
【问题讨论】:
-
您的模式似乎无法正常工作。它仍在替换 (g) 和 (test2)。
标签: python regex python-2.7