如果我有一个单词列表,如何检查字符串是否包含列表中的任何单词,并且有效?

Tho*_*eia 6 python search loops filter stop-words

正如标题所说,我有一个单词列表,喜欢stopWords = ["the", "and", "with", etc...]和我接收的文字如"杀死狐狸和狗".我希望输出像"杀死狐狸狗"非常有效和快速.我怎么能这样做(我知道我可以使用for循环迭代,但那不是很有效)

Joh*_*ooy 9

最重要的改进是使stopWords aset.这意味着查找速度非常快

stopWords = set(["the", "and", "with", etc...])
" ".join(word for word in msg.split() if word not in stopWords)
Run Code Online (Sandbox Code Playgroud)

如果您只是想知道文本中是否有任何stopWords

if any(word in stopWords for word in msg.split()):
    ...
Run Code Online (Sandbox Code Playgroud)