如何使用regex查找匹配词?

问题描述 投票:1回答:1

我在一个文本文件中有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
python regex python-3.x nlp regex-negation
1个回答
3
投票

看来你想用单纯的列表理解得到结果。

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

如果你需要一个regex(万一你打算只匹配整个单词,或者匹配你的... 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))

这个regex看起来像

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

搜索引擎演示基本上,你所有的 store 含有转义特殊字符的项目,并按长度降序排列。

© www.soinside.com 2019 - 2024. All rights reserved.