아주 간단한 토크 나이저를 만드는 방법을 알고 싶습니다. 사전 d (이 경우 목록)와 문장 s가 주어지면 문장의 가능한 모든 토큰 (= 단어)을 반환하고 싶습니다. 내가 시도한 것은 다음과 같습니다.
l = ["the","snow","ball","snowball","is","cold"]
sentence = "thesnowballisverycold"
def subs(string, ret=['']):
if len(string) == 0:
return ret
head, tail = string[0], string[1:]
ret = ret + list(map(lambda x: x+head, ret))
return subs(tail, ret)
print((list(set(subs(sentence))&set(l))))
그러나 이것은 다음을 반환합니다.
["snow","ball","cold","is","snowball","the"]
하위 문자열을 비교할 수는 있지만 더 나은 방법이 있어야합니다. 내가 원하는 것 :
["the","snowball","is","cold"]
여기에서 정규식을 활용할 수 있습니다.
import re
l = ["the","snow","ball","snowball","is","cold"]
pattern = "|".join(sorted(l, key=len, reverse=True))
sentence = "thesnowballisverycold"
print( re.findall(pattern, sentence) )
# => ['the', 'snowball', 'is', 'cold']
Python 데모를 참조하십시오 .
패턴은 다음과 같습니다 . 온라인 정규식 데모를snowball|snow|ball|cold|the|is
참조하십시오 . 트릭은 모든 대안이 가장 긴 것부터 가장 짧은 것까지 나열되도록하는 것입니다. 참조 정규 표현식 연산자의 주문 (.. | .. ... .. | ..) . 부분의 항목을 정렬 내림차순의 길이만큼, 그리고 교대 패턴을 생성한다.sorted(l, key=len, reverse=True)
l
"|".join(...)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다