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

Python中如何判断字符串是否包含数组中的元素?

问题原因与解决方案

原代码报错的核心问题有两个:

  1. 语法错误:直接将列表stop_words与字符串比较(stop_words in str),Python不支持列表和字符串的成员关系判断,因此抛出类型错误。
  2. 逻辑错误:需求是检查「是否存在任意一个停用词」,但代码使用了all()函数(要求所有停用词都在字符串中才返回True),与需求不符。

以下是几种可行的解决方案:

方案1:使用any()函数(推荐)

利用any()函数遍历停用词列表,只要有一个单词存在于字符串中就返回True,同时避免使用内置类型名str作为变量名:

text = 'Dear friends, the new model of organizational activity contributes to the preparation and implementation of the personnel training system.'
stop_words = ['training', 'moonshine']

if any(word in text for word in stop_words):
    print('Find stop word')
else:
    print('All good, no stop words')

方案2:手动遍历检查

通过循环逐个检查停用词,找到匹配后立即终止循环,适合需要额外处理匹配结果的场景:

text = 'Dear friends, the new model of organizational activity contributes to the preparation and implementation of the personnel training system.'
stop_words = ['training', 'moonshine']
has_stop_word = False

for word in stop_words:
    if word in text:
        has_stop_word = True
        break

print('Find stop word' if has_stop_word else 'All good, no stop words')

方案3:完整单词匹配(避免子串误判)

如果需要严格匹配完整单词(比如不想让train匹配training),可以使用正则表达式的单词边界:

import re

text = 'Dear friends, the new model of organizational activity contributes to the preparation and implementation of the personnel training system.'
stop_words = ['training', 'moonshine']
# 构建正则模式,转义特殊字符并添加单词边界
pattern = re.compile(r'\b(' + '|'.join(re.escape(word) for word in stop_words) + r')\b')

if pattern.search(text):
    print('Find stop word')
else:
    print('All good, no stop words')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:50:25