2013-03-15 92 views
6

我試圖使用編譯的正則表達式匹配並從列表中刪除列表中的所有單詞,但我努力避免單詞中的出現。從python列表中刪除字符串中出現的所有字詞

電流:

REMOVE_LIST = ["a", "an", "as", "at", ...] 

remove = '|'.join(REMOVE_LIST) 
regex = re.compile(r'('+remove+')', flags=re.IGNORECASE) 
out = regex.sub("", text) 

在:

出 「敏捷的棕色狐狸比一隻螞蟻躍升」:「敏捷的棕色狐狸跳過T」

預期:「快速的棕色狐狸跳過」

我試圖改變字符串編譯以下,但無濟於事:

regex = re.compile(r'\b('+remove+')\b', flags=re.IGNORECASE) 

任何建議或我思念的東西華麗地明顯?

+0

想必'ant'是屬於你刪除列表? – 2013-03-15 15:07:57

回答

8

一個問題是隻有第一個\b位於原始字符串內部。第二個被解釋爲退格字符(ASCII 8)而不是字邊界。

要修復,改變

regex = re.compile(r'\b('+remove+')\b', flags=re.IGNORECASE) 

regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE) 
           ^THIS 
+1

作爲一個技巧來發現這個(除了事先知道這一點),輸出模式與'regex.pattern' – nhahtdh 2013-03-15 15:14:10

+0

不錯的一個NPE。謝謝! – Ogre 2013-03-15 15:15:07

16

這裏是不使用正則表達式的建議,你可能要考慮:

>>> sentence = 'word1 word2 word3 word1 word2 word4' 
>>> remove_list = ['word1', 'word2'] 
>>> word_list = sentence.split() 
>>> ' '.join([i for i in word_list if i not in remove_list]) 
'word3 word4' 
+0

Groovy。沒有想到這一點。謝謝:) – Ogre 2013-03-15 15:21:59

+0

值得指出的是,這將有困難與標點符號,並不會保留製表符/連續的空格(不知道如果後者是重要的)。 – NPE 2013-03-15 15:23:21

+3

值得注意的是,如果'remove_list'很大,那麼使用'remove_set = {'word1','word2',...}'會更好,因爲集合會有更快的成員資格測試。 – 2013-03-15 15:24:58

相關問題