我有以下示例字符串:
这是对场外电力损失的考验。
我有以下标签:
场外电力,场外电力损失
我试着从绳子上得到所有的火柴。但是,当我有以下代码时:
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']我需要得到标记的两个实例。我知道我可以通过循环遍历每个标签,然后搜索每个标签上的描述,但是在一个搜索中有什么方法可以做到吗?
我的代码是Python2.7,但是我也会接受Python 3的答案。
注意:我的最后关键字列表大约有2000个短语,类似于上面的内容。
发布于 2016-04-20 15:44:37
非常简单:使用Matthew更新的regex模块,它允许重叠匹配。在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()。
https://stackoverflow.com/questions/36748572
复制相似问题