programing

다른 문자열의 단어 목록 확인

telecom 2023. 5. 25. 21:32
반응형

다른 문자열의 단어 목록 확인

나는 파이썬에서 그런 것을 할 수 있습니다.

l = ['one', 'two', 'three']
if 'some word' in l:
   ...

목록에 '어떤 단어'가 있는지 확인합니다.하지만 제가 반대로 할 수 있을까요?

l = ['one', 'two', 'three']
if l in 'some one long two phrase three':
    ...

나는 배열에서 나온 단어들이 문자열에 있는지 확인해야 합니다.사이클을 사용하여 할 수 있지만 이 방법은 코드 줄이 더 많습니다.

if any(word in 'some one long two phrase three' for word in list_):

여기 케니보다 더 빠르거나 더 적합할 수 있는 몇 가지 대안적인 방법이 있습니다.상황에 따라 TM의 답변.

정규식 사용:

import re
words_re = re.compile("|".join(list_of_words))

if words_re.search('some one long two phrase three'):
   # do logic you want to perform

전체 단어를 일치시키려면 집합을 사용할 수 있습니다. 예를 들어 "the the theory"라는 단어를 "the the theory"라는 문구에서 찾고 싶지 않은 경우:

word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
    # do stuff

물론 "\b" 토큰을 사용하여 정규식으로 전체 단어 일치를 수행할 수도 있습니다.

이것들과 케니의 솔루션의 성능은 단어 목록과 구문 문자열의 길이, 변경 빈도와 같은 몇 가지 요인에 따라 달라질 것입니다.성능이 문제가 되지 않는다면 가장 단순한 것을 선택하십시오. 이것은 아마도 케니의 것일 것입니다.

단어 목록의 길이가 상당하고 이 테스트를 여러 번 수행해야 하는 경우 목록을 집합으로 변환하고 집합 교차점을 사용하여 테스트하는 것이 좋습니다(두 목록에 있는 실제 단어를 얻을 수 있다는 추가 이점).

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

이 문제를 해결하는 가장 쉽고 간단한 방법은 재사용입니다.

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE makes the search case-insensitive
    # Do Something if word is present
else:
    # Do Something else if word is not present

언급URL : https://stackoverflow.com/questions/3271478/check-list-of-words-in-another-string

반응형