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

时间:2012-01-20 18:26:10

标签: python coding-style logic

我有一些包含一些文字的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中的所有单词是否都在theTextContent中。在我看来,这太笨重了,不能成为优秀的Python代码

非常感谢任何见解

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:5)

if all(word in theTextContents.split() for word in myWords):
    ...
Python 2.5 +中的

all函数

答案 2 :(得分:3)

尝试:

myWords=['some', 'supplied','words']
theTextContents='a string that might or might not have all of some supplied words'
goodElements=[]

splitted = theTextContents.split()
if all(word in splitted for word in myWords):
    goodElements.append(theTextContents)