В моей программе я нахожу n-грамм и распечатываю, сколько их в наборе данных.https://en.wikipedia.org/wiki/N-gram Для тех, кто не знает, что такое n-грамм.
Вот мой код:
from collections import defaultdict
import sys
from string import punctuation
def tokenize(text, ngrams=1):
tokens = text.split()
return [tuple(tokens[i:i+ngrams]) for i in range(len(tokens)-ngrams+1)]
line = ""
for i in sys.stdin:
stripped = i.strip(punctuation)
line += stripped.lower()
for n in range(1, 10):
a = tokenize(line, n)
d = defaultdict(int)
for i in a:
d[i] += 1
result = max(d.items(), key = lambda x: x[1])
if(result[1] >= 3):
s = ' '.join(result[0])
print('{:<6} {:<0} {:<0} {:<10}'.format(str(result[1]), str(n) + "-grams ", "|", s))
Вот пример выходных данных моей программы с набором данных:
10 1-grams | and
3 2-grams | balloonman whistles
3 3-grams | balloonman whistles far
3 4-grams | balloonman whistles far and
3 5-grams | balloonman whistles far and wee
И вот что я должен получить (не обращая внимания на различия в форматировании):
10 1-grams | and
3 2-grams | balloonman whistles
3 2-grams | whistles far
3 2-grams | far and
3 2-grams | and wee
3 3-grams | balloonman whistles far
3 3-grams | whistles far and
3 3-grams | far and wee
3 4-grams | balloonman whistles far and
3 4-grams | whistles far and wee
3 5-grams | balloonman whistles far and wee
Кажется, проблема в том, что я нахожу максимум своих предметов в моем defaultdict,Например, я получаю только 3 из 3 граммов, но я хочу получить все 3 3 грамма.Есть идеи?Заранее спасибо