我必須匹配文本中的所有字母數字單詞。python正則表達式可否定單詞列表嗎?
>>> import re
>>> text = "hello world!! how are you?"
>>> final_list = re.findall(r"[a-zA-Z0-9]+", text)
>>> final_list
['hello', 'world', 'how', 'are', 'you']
>>>
這很好,但我進一步否定了不應該在我的最終名單中的單詞。
>>> negate_words = ['world', 'other', 'words']
一個糟糕的方式做到這一點
>>> negate_str = '|'.join(negate_words)
>>> filter(lambda x: not re.match(negate_str, x), final_list)
['hello', 'how', 'are', 'you']
但我可以節省一個循環,如果我的第一個正則表達式模式是可以改變的考慮的那些話否定。我發現否定字符,但我有話否定,也發現正則表達式在其他問題,但這也沒有幫助。
是否可以使用python re?
更新
我的文字可以跨越幾個hundered線。此外,negate_words列表也可能很長。
考慮到這一點,正在使用正則表達式來處理這樣的任務,正確的處於第一位?有什麼建議?
有很多'negate_words'的? –
@bitsMiz是的,可以有很多否定詞。文本也可以跨越很少的線條。 – simplyharsh