gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:08:02 24 4
gpt4 key购买 nike

我有一个要在文本中查找的单词列表 (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_list 中列出的表达式并获得像这样的 final_list:

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

final_list 和 scape_list 一直在更新。所以我认为正则表达式是一个很好的方法。

最佳答案

您可以使用正则表达式捕获 find_list 单词前后的单词,并检查这两个组合是否不存在于 scape_list 中。我在更改代码的地方添加了注释。 (最好将 scape_list 更改为 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']

关于当搜索到的词在定义的表达式中时,python 绕过 re.finditer 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65724901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com