用python构造字母组合,二元组和三元组

问题描述 投票:0回答:1

如何为大型语料库构造单字组,二元组和三元组,然后计算它们的频率。按最频繁到最不常见的克数排列结果。

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)```
python nltk
1个回答
1
投票

尝试一下:

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)
© www.soinside.com 2019 - 2024. All rights reserved.