首页 > 解决方案 > Python替换功能不替换所有单词

问题描述

我有一个要从字符串中过滤掉的单词/短语列表。但是,我的代码并没有过滤掉所有的单词。为什么会这样?

stop_words = ['nbsp']
string = 'applicant nbsp entrepreneur nbsp develop level nbsp export artist nbsp export entrepreneur nbsp record label nbsp nbsp music publisher nbsp nbsp music manager'

for word in stop_words:
    if word in string:
        string = re.sub(" {} ".format(word), " ", string)
print(string)

运行此代码后,这是输出。

'applicant entrepreneur develop level export artist export entrepreneur record label nbsp music publisher nbsp music manager'

如您所见,'nbsp' 仍在字符串中。此外,在我的实际停用词列表中,列表中的元素长度超过一个单词。例如,“睡觉”是一个元素。我也没有省略单词两侧的空格,这样单字母大小写(例如“a”)就不会从带有“a”的单词中过滤掉。

标签: pythonregexstringreplace

解决方案


推荐阅读