查找python中许多元素中的第一个元素-text.Find(a、b、c)

查找python中许多元素中的第一个元素-text.Find(a、b、c),text,scripting,find,python,Text,Scripting,Find,Python,我想检查a中的一个单词是否在文本中 text = "testing if this works" a = ['asd' , 'test'] print text.find(a) 我该怎么做 谢谢如果您想检查a中的任何单词是否在文本中,请使用: 如果您想知道文本中出现的单词数,您可以简单地: 如果只想匹配完整单词,即不想匹配测试单词测试,请将文本拆分为单词,如中所示: words = set(text.split()) any(word in words for word in a) 如果要

我想检查a中的一个单词是否在文本中

text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
我该怎么做


谢谢

如果您想检查a中的任何单词是否在文本中,请使用:

如果您想知道文本中出现的单词数,您可以简单地:

如果只想匹配完整单词,即不想匹配测试单词测试,请将文本拆分为单词,如中所示:

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

如果要检查a中的任何单词是否在文本中,请使用:

如果您想知道文本中出现的单词数,您可以简单地:

如果只想匹配完整单词,即不想匹配测试单词测试,请将文本拆分为单词,如中所示:

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

正则表达式可用于在单个过程中搜索多个匹配模式:

>>> 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

正则表达式可用于在单个过程中搜索多个匹配模式:

>>> 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

@劳伦斯没有冒犯你,但是你的编辑改变了这个答案的意思。另外,对于大量的单词和不断分割文本的非优化Python解释器来说,这将是非常低效的。已添加您的版本,但已提前优化。抱歉。我把这个问题理解为想要搜索整个单词,所以尝试进行最小的编辑以适应这种解释。回过头来看,我发现这个问题实际上是模棱两可的。@Laurence Gon无意冒犯,但你的编辑将这个答案的意思改变了很多。另外,对于大量的单词和不断分割文本的非优化Python解释器来说,这将是非常低效的。已添加您的版本,但已提前优化。抱歉。我把这个问题理解为想要搜索整个单词,所以尝试进行最小的编辑以适应这种解释。回顾过去,我发现这个问题实际上是模棱两可的。
>>> 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