Skip to main content
 首页 » 编程设计

python之测试字符串内容的更好逻辑

2025年05月04日19kenshinobiy

我有一个包含一些文本的 html 元素列表。我需要找到包含我要提供的所有单词的元素。我有一些代码可以完成我想要的,但我相信有更好的方法可以做到这一点

myWords=['some', 'supplied','words'] 
theTextContents='a string that might or might not have all of some supplied words' 
goodElements=[] 
count=0 
for word in myWords: 
    if word in TheTextContents: 
    count+=1 
if count==len(myWords): 
    goodElements.append(theTextContents) 

还有很多代码,但这是我们测试以查看 MyWords 中的所有单词是否都在 TextContent 中的基本方法。在我看来,这太笨重了,不是好的 Python 代码

任何见解将不胜感激

请您参考如下方法:

if set(theTextContents.split()) >= set(myWords): 
    ...