python - 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”的单词中过滤掉。
解决方案
推荐阅读
- php - 将数据插入表中的最用户友好的方式
- mysql - 我试图让分配了某些东西的用户能够使用 PHP 和 MYSQL 查看它
- javascript - 在 React 中旋转 3 页
- javascript - 如何使用 Webpack 4 仅在某些模块中导入 jQuery?
- node.js - 异步编程中的迭代 (Node.js)
- angular - 现有项目上的 Angular 通用
- windows - 使用批处理文件重命名
- django - 如何创建 Django 数据库备份?
- bash - 在 Bash 中出现 5 次逗号后向文本文件添加新行
- python - tensorflow通过随机因子调整图像大小