이 부분을 두 부분으로 나눕니다.
def ngrams(l, n):
return list(zip(*[l[i:] for i in range(n)]))
우리는 이제 쉽게 2, 3 또는 4 그램을 얻을 수 있습니다 :
>>> ngrams(["car", "hello","bye" ,"hello"], 2)
[('car', 'hello'), ('hello', 'bye'), ('bye', 'hello')]
>>> ngrams(["car", "hello","bye" ,"hello"], 3)
[('car', 'hello', 'bye'), ('hello', 'bye', 'hello')]
>>> ngrams(["car", "hello","bye" ,"hello"], 4)
[('car', 'hello', 'bye', 'hello')]
첫째, 우리는 주어진리스트의을
ngrams를 반환하는 기능을 설정, 즉, n 개의 연속적인 요소의 하위 목록입니다 각 항목은 튜플로 구성됩니다.
지금 튜플에 문구 'hello bye'
합니다이 두 단어를 가지고 있기 때문에 >>> as_tuple = tuple('hello bye'.split())
>>> as_tuple
('hello', 'bye')
>>> len(as_tuple)
2
, 우리는 문장에서 bigrams을 생성하고, 일치하는 bigrams의 수를 계산해야합니다.이 모든 것을 일반화 할 수 있습니다.
def ngrams(l, n):
return list(zip(*[l[i:] for i in range(n)]))
def count_occurrences(sentence, phrase):
phrase_as_tuple = tuple(phrase.split())
sentence_ngrams = ngrams(sentence, len(phrase_as_tuple))
return sentence_ngrams.count(phrase_as_tuple)
print(count_occurrences(["car", "hello","bye" ,"hello"], 'hello bye'))
# prints 1
[XY 문제] (http://meta.stackexchange.com/a/66378/344593)와 같이 들립니다.이 코드로 해결하려는 문제를 설명해 주시겠습니까? 핵심 이슈에 대한 더 쉬운 해결책이있을 수 있습니다. – TemporalWolf
열거 형의 for 루프를 사용하여 내용 * 및 * 색인을 유지할 수 있습니다. http://stackoverflow.com/questions/22171558/what-does-enumerate-mean –