You need to enable JavaScript to run this app. 如何使用re模块删除字符串中包含指定子串的所有原字符单元?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用re模块删除字符串中包含指定子串的所有原字符单元?

实现思路

  • 先把原始字符串按逗号切分为独立的文本单元,去除每个单元两端的空白字符
  • 将敏感词统一转为小写,后续匹配时忽略大小写
  • 遍历每个文本单元,只要单元的小写形式包含任意一个小写敏感词,就直接丢弃该单元
  • 把保留下来的单元用逗号拼接,得到最终结果

可直接运行的代码

badwords = ['qanon', 'trump', 'corona', 'COVID']
# 敏感词统一转小写,实现忽略大小写匹配
badwords_lower = [word.lower() for word in badwords]
origin_str = "'Patriots', 'corona2020','COVID-19','coronavirus','2020TRUmp','Support2020Trump','whitehouse','Trump2020','QAnon','QAnon2020',TrumpQanon"

keep_units = []
for unit in origin_str.split(','):
    unit_stripped = unit.strip()
    unit_lower = unit_stripped.lower()
    # 仅保留不包含任何敏感词的单元
    if not any(bad_word in unit_lower for bad_word in badwords_lower):
        keep_units.append(unit_stripped)

# 拼接得到最终结果
result = ','.join(keep_units)
print(result)

运行后输出结果为:'Patriots','whitehouse',完全符合预期。

原有代码问题说明

你写的正则仅匹配了「敏感词前有字母数字」或「敏感词后有字母数字」的场景,没有覆盖敏感词在单元中间的情况,也没有实现删除敏感单元的逻辑,因此无法得到正确结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 07:36:09