从python列表中删除字符串中出现的所有单词

时间:2013-03-15 15:06:07

标签: python regex

我正在尝试使用已编译的正则表达式匹配并删除列表中的所有单词,但我正在努力避免在单词中出现。

电流:

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

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

在:“快速的棕色狐狸跳过一只蚂蚁”

Out:“快速棕色狐狸跳过t”

预期:“快速棕色狐狸跳过”

我已经尝试更改字符串以编译为以下但无效:

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

有任何建议或者我错过了一些非常明显的东西吗?

2 个答案:

答案 0 :(得分:18)

这是一个不使用正则表达式的建议,您可能需要考虑:

>>> 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'

答案 1 :(得分:11)

一个问题是只有第一个\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
相关问题