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

2024-04-20 13:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用编译的regex匹配并从字符串中删除列表中的所有单词,但我正在努力避免单词中出现。

当前:

 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)

有什么建议吗?还是我遗漏了一些显而易见的东西?


Tags: 字符串rean列表as单词removelist
2条回答

以下建议不使用regex,您可能需要考虑:

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

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

相关问题 更多 >