我有以下示例字符串:
this is a test of the loss of offsite power
我有以下标签:
offsite power, loss of offsite power
我正在尝试从字符串中获取所有匹配项。但是当我有这段代码时:
import re
description = 'this is a test of the loss of offsite power'
all_tags = ['offsite power', 'loss of offsite power']
reg_ex = '|'.join(['\\b%s\\b' % t for t in all_tags])
expression = re.compile(reg_ex, re.IGNORECASE)
matches = re.findall(expression, description)
results = [m for m in matches]
print results
我的结果如下:
['loss of offsite power']
我需要获取标签的两个实例。我知道我可以通过遍历每个标签然后搜索每个标签的描述来做到这一点,但是有没有办法在一次搜索中做到这一点?
我的代码适用于 Python 2.7,但我也接受 Python 3 的答案。
注意:我的最终关键词列表大约有 2000 个与上述类似的词组。
最佳答案
非常简单:使用较新的 regex
Matthew Barnett 的模块允许重叠匹配。在 Python
中:
import regex as re
string = 'this is a test of the loss of offsite power'
all_tags = ['offsite power', 'loss of offsite power']
reg_ex = '|'.join(['\\b%s\\b' % t for t in all_tags])
expression = re.compile(reg_ex, re.IGNORECASE)
# mind overlapped=True !
matches = re.findall(expression, string, overlapped=True)
print matches
# ['loss of offsite power', 'offsite power']
要获取模块,只需在命令行上执行 pip install regex
。它也适用于 re.finditer()
。
关于regex - 当模式具有相似文本时,如何使用 RegEx 在 Python 中获取所有匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36748572/