Python正则表达式匹配列表中的多个单词

2023-12-09

我有一个单词列表和一个字符串,并且想从原始列表中取回在字符串中找到的单词列表。

Ex:

import re

lof_terms = ['car', 'car manufacturer', 'popular']
str_content = 'This is a very popular car manufacturer.'

pattern = re.compile(r"(?=(\b" + r"\b|".join(map(re.escape, lof_terms)) + r"\b))")
found_terms = re.findall(pattern, str_content)

这只会返回 ['car', 'popular']。它未能抓住“汽车制造商”。但是,如果我将术语源列表更改为lof_terms = ['car manufacturer', 'popular']

不知何故,“汽车”和“汽车制造商”之间的重叠似乎是这个问题的根源。

有什么想法如何克服这个问题吗?

非常感谢


如果您首先对当前代码进行排序,则可以修复当前代码lof_terms按长度降序排列:

rx = r"(?=\b({})\b)".format("|".join(map(re.escape, sorted(lof_terms, key=len, reverse=True))))
pattern = re.compile(rx)

请注意,在这种情况下,\b单词边界仅在分组的两端使用一次,无需在每个替代项周围重复它们。看这个正则表达式演示.

See the Python演示:

import re

lof_terms = ['car', 'car manufacturer', 'popular']
str_content = 'This is a very popular car manufacturer.'

rx = r"(?=\b({})\b)".format("|".join(map(re.escape, sorted(lof_terms, key=len, reverse=True))))
pattern = re.compile(rx)
found_terms = re.findall(pattern, str_content)
print(found_terms)
# => ['popular', 'car manufacturer']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python正则表达式匹配列表中的多个单词 的相关文章

随机推荐