当搜索的词位于定义的表达式中时,python会绕过re.finditer匹配

2024-04-20 10:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我想在文本中找到的单词列表(find_list)和一个表达式列表,其中包含我想在文本中绕过的单词(scape_list)

我可以使用以下代码找到文本中的所有单词:

find_list = ['name', 'small']
scape_list = ['small software', 'company name']

text = "My name is Klaus and my middle name is Smith. I work for a small company. The company name is Small Software. Small Software sells Software Name."

final_list = []

for word in find_list:
    
    s = r'\W{}\W'.format(word)
    matches = re.finditer(s, text, (re.MULTILINE | re.IGNORECASE))

    for word_ in matches:
        final_list.append(word_.group(0))

最后的清单是:

[' name ', ' name ', ' name ', ' Name.', ' small ', ' Small ', ' Small ']

有没有一种方法可以绕过scape_列表中列出的表达式并获得最终的_列表,如下所示:

[' name ', ' name ', ' Name.', ' small ']

最终列表和景观列表总是在更新。所以我认为正则表达式是一个很好的方法


1条回答
网友
1楼 · 发布于 2024-04-20 10:35:45

您可以使用正则表达式捕获find_list单词前后的单词,并检查scape_list中是否不存在这两个组合。我在更改代码的地方添加了注释。(最好将scape_列表更改为set,如果它将来可以变大的话)

find_list = ['name', 'small']
scape_list = ['small software', 'company name']

text = "My name is Klaus and my middle name is Smith. I work for a small company. The company name is Small Software. Small Software sells Software Name."

final_list = []

for word in find_list:
    
    s = r'(\w*\W)({})(\W\w*)'.format(word) # change the regex to capture adjacent words
    matches = re.finditer(s, text, (re.MULTILINE | re.IGNORECASE))

    for word_ in matches:
        if ((word_.group(1) + word_.group(2)).strip().lower() not in scape_list
            and (word_.group(2) + word_.group(3)).strip().lower() not in scape_list): # added this condition
            final_list.append(word_.group(2)) # changed here

final_list
['name', 'name', 'Name', 'small']

相关问题 更多 >