You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python字符串移除代码,实现子串匹配式停用词移除?

实现移除包含指定停用词的单词

原代码仅支持停用词与单词完全匹配时的移除,要实现只要单词包含停用词(不区分大小写)就移除的需求,需要修改过滤逻辑:

将原列表推导式中的完全匹配判断,改为检查任意停用词是否是当前单词小写形式的子串。

修改后的代码如下:

name = 'NAMEde What if i dos'
stopwords = ['name', 'do']
querywords = name.split()

# 只要单词小写后包含任意一个停用词,就排除该单词
resultwords = [word for word in querywords if not any(stopword in word.lower() for stopword in stopwords)]
result = ' '.join(resultwords)

print(result)  # 输出: What if i

关键逻辑说明

  • word.lower():将当前单词转为小写,实现大小写不敏感的匹配
  • any(stopword in word.lower() for stopword in stopwords):遍历停用词列表,只要有一个停用词是当前单词的子串,就返回True
  • 前缀not:表示当存在匹配的停用词时,不将该单词加入结果列表

内容的提问来源于stack exchange,提问作者jelkaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:23:09