在Python中使用regex.findall的列表交集的完全匹配
问题描述:
我想要使用正则表达式获取单词列表的交集。它的C实现使得它在这种特殊情况下运行更加快速......尽管我的代码几乎可以工作,但它也可以匹配“embeded-words”,比如“buyers”和“buy”。在Python中使用regex.findall的列表交集的完全匹配
某些代码可能更好地解释它。这是我到目前为止有:
re.findall(r"(?=(" + '|'.join(['buy', 'sell', 'gilt']) + r"))", ' '.join(['aabuya', 'gilt', 'buyer']))
>> ['buy', 'gilt', 'buy']
虽然这是我想什么:
re.exactfindall(['buy', 'sell', 'gilt'], ['aabuya', 'gilt', 'buyer'])
>>['gilt']
感谢。
答
要做到这一点使用正则表达式,最简单的方法可能是包括在匹配表达断字(\b
),(捕捉外)给你:
re.findall(r"\b(?=(" + '|'.join(['buy', 'sell', 'gilt']) + r")\b)",
' '.join(['aabuya', 'gilt', 'buyer']))
的要求,输出['gilt']
。
+0
太棒了!而已。谢谢! – ylnor
答
listgiven=['aabuya', 'gilt', 'buyer']
listtomatch=['buy', 'sell', 'gilt']
exactmatch = [x for x in listgiven if x in listtomatch]
print(exactmatch)
+0
谢谢,但由于正则表达式在C中实现并运行得更快,所以我宁愿尝试使用regex.findall找到解决方案,如果可能的话... – ylnor
如果我理解正确,你基本上是寻找两个列表的交集?(一个是你的列表从句子,另一个是给定的列表。)在这里看到答案:http://stackoverflow.com/questions/3697432/如何找到列表交集 – xbb
我在这里谈论正则表达式。但是,谢谢 – ylnor