【问题标题】:Python Regex - Making an exception involving two text filesPython Regex - 涉及两个文本文件的异常
【发布时间】: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


【解决方案1】:

撇开您发布的模式中的一些错误(我不知道这对给定示例如何为您工作),关于策略,您可以将所有异常添加到列表中,并且一旦遍历这两个文件,追加新的异常(两个文件中都出现)并通过将所有异常(异常)插入到其中来编译正则表达式表达式 '|' 加入字符。

此代码适用于我。

import re

exceptions=['test2','test4','g']
pattern1 = re.compile(r"(\((?!"+'|'.join(ex for ex in exceptions)+")[\w+ :]+\))")

with open("text2.txt", "r") as f:
    words = pattern1.findall(f.read())
    print(words)

with open("text1.txt", "r+") as f:
    text = f.read()
    for line in text.splitlines():
        if line in words:
            new_exception =  re.search(r'\(([\w+ :]+)\)',line)
            exceptions.append(new_exception.group(1))
            words.remove(line)

    all_exceptions_compiled = re.compile(r"(\((?!"+'|'.join(ex for ex in exceptions)+")[\w+ :]+\))")
    content = all_exceptions_compiled.sub(lambda x: words.pop(0) if words else x.group(), text)
    f.seek(0)
    f.write(content)
    f.truncate()

请记住,我已通过以下方式修改了您的正则表达式模式:(\((?!test2|g|test4)[\w+ :]+\))

此代码在列表上实现迭代 (On) 和删除 (On) 操作,根据 n 的大小,这不是一个有效的解决方案。如果性能是一个需要考虑的因素,你应该改进这部分。

【讨论】:

  • 非常感谢。那太完美了。
  • @legXen 如果是这样,请随时将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 2011-06-28
  • 2016-10-25
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多