【问题标题】:How to find matching words using regex?如何使用正则表达式查找匹配的单词?
【发布时间】:2020-04-29 11:41:49
【问题描述】:

我的文本文件中有超过 2000 行的字符串,例如:

cool.add.come.ADD_COPY
add.cool.warm.ADD_IN
warm.cool.warm.MINUS
cool.add.go.MINUS_COPY

我有一个包含 200 多个匹配词的列表,例如:

store=['ADD_COPY','add.cool.warm.ADD_IN', 'warm.cool.warm.MINUS', 'MINUS_COPY']

我在代码中使用正则表达式

def all(store, file):
    lst=[]
    for match in re.finditer(r'[\w.]+', file):
        words = match.group()
            if words in store:
                lst.append(words) 
    return lst 

然后我在一个循环中检查需求。

我得到的输出:

add.cool.warm.ADD_IN
warm.cool.warm.MINUS

如果我将标识符更改为 \w+,那么我只会得到:

ADD_COPY
MINUS_COPY

需要的输出:

add.cool.warm.ADD_IN
warm.cool.warm.MINUS   
ADD_COPY
MINUS_COPY

【问题讨论】:

  • @RishiDev 绝对不是,字符类中的. 总是匹配文字.
  • 这个问题包含重现问题的所有细节。它只是漏掉了两个冒号。

标签: python regex python-3.x nlp regex-negation


【解决方案1】:

您似乎想仅使用列表理解来获得结果:

results = set([item for item in store if item in text])

如果您需要正则表达式(如果您打算仅匹配整个单词,或仅在特定上下文中匹配 store 项目),您可以使用

import re
text="""cool.add.come.ADD_COPY
add.cool.warm.ADD_IN
warm.cool.warm.MINUS
cool.add.go.MINUS_COPY"""

store=['ADD_COPY','add.cool.warm.ADD_IN', 'warm.cool.warm.MINUS', 'MINUS_COPY']
rx="|".join(sorted(map(re.escape, store), key=len, reverse=True))
print(re.findall(rx, text))

正则表达式看起来像

add\.cool\.warm\.ADD_IN|warm\.cool\.warm\.MINUS|MINUS_COPY|ADD_COPY

查看regex demo,基本上是所有store 带有转义特殊字符并按长度降序排序的项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多