我要检查,如果在“a”是内“文本”查找蟒蛇 - text.find(A,B,C)
text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
我该怎么办一家之言这个?
感谢
我要检查,如果在“a”是内“文本”查找蟒蛇 - text.find(A,B,C)
text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
我该怎么办一家之言这个?
感谢
In [20]: wordset = set(text.split())
In [21]: any(w in wordset for w in a)
Out[21]: False
的正则表达式可以用来在单次搜索多个匹配模式:
>>> 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
@Laurence Gonsalves没有冒犯,但你的编辑改变了这个答案的含义很多。另外,大量的单词和一个非优化的Python解释器会不断分割文本,效率会很低。添加了您的版本,但事先进行了优化。 – phihag 2012-01-16 18:37:32
对不起。我将这个问题看成是想要搜索整个单词,所以试图使最小的编辑适合这种解释。回顾一下,我发现问题实际上是模棱两可的。 – 2012-01-16 20:40:48