私は言葉の一つが「」「テキスト」検索 - text.find(a、b、c)は、
text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
私はどのように行うことができます内にある中かどうかを確認したいですこの?
おかげ
私は言葉の一つが「」「テキスト」検索 - text.find(a、b、c)は、
text = "testing if this works"
a = ['asd' , 'test']
print text.find(a)
私はどのように行うことができます内にある中かどうかを確認したいですこの?
おかげ
あなたはa
の単語のいずれかがテキストであるかどうかを確認したい場合は、使用、よく、any
:
any(word in text for word in a)
あなたはa
その中で単語の数を知りたい場合はあなただけの完全な言葉を一致させたい場合は
print('Number of words in a that match text: %s' %
sum(word in text for word in a))
:あなたができるだけでadd
彼らは、テキストで発生(すなわち、あなたはtest
単語testing
)と一致したくない、のように、言葉にテキストを分割:
words = set(text.split())
any(word in words for word in 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
申し訳ありません。私は単語全体を検索したいという質問を読んで、その解釈に合うように最小限の編集をしようとしました。振り返ると、その質問は実際にはあいまいであることがわかります。 –