我有一个包含一些文本的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代码
如果您有任何见解,我们将不胜感激
发布于 2012-01-21 02:32:06
if all(word in theTextContents.split() for word in myWords):
...Python 2.5+中的all函数
发布于 2012-01-21 02:36:10
if set(theTextContents.split()) >= set(myWords):
...发布于 2012-01-21 02:37:17
尝试:
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)https://stackoverflow.com/questions/8946078
复制相似问题