我必须匹配文本中的所有字母数字单词。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