2017-05-04 113 views
0

我想要使用正則表達式獲取單詞列表的交集。它的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'] 

感謝。

+0

如果我理解正確,你基本上是尋找兩個列表的交集?(一個是你的列表從句子,另一個是給定的列表。)在這裏看到答案:http://stackoverflow.com/questions/3697432/如何找到列表交集 – xbb

+0

我在這裏談論正則表達式。但是,謝謝 – ylnor

回答

1

要做到這一點使用正則表達式,最簡單的方法可能是包括在匹配表達斷字(\b),(捕捉外)給你:

re.findall(r"\b(?=(" + '|'.join(['buy', 'sell', 'gilt']) + r")\b)", 
    ' '.join(['aabuya', 'gilt', 'buyer'])) 

的要求,輸出['gilt']

+0

太棒了!而已。謝謝! – ylnor

0
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