构建 python 中的一元、二元和三元

construct the unigrams, bi-grams and tri-grams in python

如何为大型语料库构造一元词、二元词和三元词,然后计算它们各自的频率。按最频繁到最不频繁的克数排列结果。

from nltk import word_tokenize
from nltk.util import ngrams
from collections import Counter

text = "I need to write a program in NLTK that breaks a corpus (a large collection of \
txt files) into unigrams, bigrams, trigrams, fourgrams and fivegrams.\ 
I need to write a program in NLTK that breaks a corpus"
token = nltk.word_tokenize(text)
bigrams = ngrams(token,2)
trigrams = ngrams(token,3)```

试试这个:

import nltk
from nltk import word_tokenize
from nltk.util import ngrams
from collections import Counter

text = '''I need to write a program in NLTK that breaks a corpus (a large 
collection of txt files) into unigrams, bigrams, trigrams, fourgrams and 
fivegrams. I need to write a program in NLTK that breaks a corpus'''

token = nltk.word_tokenize(text)
most_frequent_bigrams = Counter(list(ngrams(token,2))).most_common()
most_frequent_trigrams = Counter(list(ngrams(token,3))).most_common()
for k, v in most_frequent_bigrams:
    print (k,v)
for k, v in most_frequent_trigrams:
    print (k,v)