2012-01-16 111 views

回答

5

如果你要检查所有的a的话是否是在文本,使用好,any

any(word in text for word in a) 

如果你想知道a单词的数量出现在文本中,你可以简单地add他们:

print('Number of words in a that match text: %s' % 
     sum(word in text for word in a)) 

如果你想只匹配完整的单词(即你不想匹配testtesting),分裂文成词,如:

words = set(text.split()) 
any(word in words for word in a) 
+0

@Laurence Gonsalves没有冒犯,但你的编辑改变了这个答案的含义很多。另外,大量的单词和一个非优化的Python解释器会不断分割文本,效率会很低。添加了您的版本,但事先进行了优化。 – phihag 2012-01-16 18:37:32

+0

对不起。我将这个问题看成是想要搜索整个单词,所以试图使最小的编辑适合这种解释。回顾一下,我发现问题实际上是模棱两可的。 – 2012-01-16 20:40:48

1
In [20]: wordset = set(text.split()) 

In [21]: any(w in wordset for w in a) 
Out[21]: False 
2

的正则表达式可以用来在单次搜索多个匹配模式:

>>> import re 
>>> a = ['asd' , 'test'] 
>>> regex = re.compile('|'.join(map(re.escape, sorted(a, key=len, reverse=True)))) 

>>> print bool(regex.search(text))  # determine whether there are any matches 
True 
>>> print regex.findall(text)   # extract all matching text 
['test'] 
>>> regex.search(text).start()   # find the position of the first match 
0