Jim*_*asa 1 python scripting text find
我想检查"a"中的一个单词是否在"text"中
text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
谢谢
如果要检查a文本中是否有任何单词,请使用,以及any:
any(word in text for word in a)
Run Code Online (Sandbox Code Playgroud)
如果您想知道a文本中出现的单词数,您可以简单地add说:
print('Number of words in a that match text: %s' %
sum(word in text for word in a))
Run Code Online (Sandbox Code Playgroud)
如果您只想匹配完整的单词(即您不想匹配test单词testing),请将文本拆分为单词,如下所示:
words = set(text.split())
any(word in words for word in a)
Run Code Online (Sandbox Code Playgroud)