我的代码应输出语料库中频率最高的前10个单词。但是,它给出了10个随机字的输出。
from nltk.corpus import brown
import operator
brown_tagged_sentences = brown.tagged_sents(categories='news')
fd=nltk.FreqDist(brown.words(categories='news'))
sorted_fd = dict(sorted(fd.items(), key=operator.itemgetter(1), reverse=True))
print(sorted_fd)
most_freq_words=list(sorted_fd)[:10]
for word in most_freq_words:
print(word,':',sorted_fd[word])
目前的输出低于错误:
Rae : 1
discharge : 1
ignition : 1
contendere : 1
done : 24
meaning : 4
ashore : 1
Francesca : 1
Vietnamese : 1
data : 4
请帮助
答案 0 :(得分:2)
nltk的FreqDist()
类可以使用most_common()
方法直接按频率降序给出内容:
fd=nltk.FreqDist(brown.words(categories='news'))
for w, f in fd.most_common(10):
print(w+":", f)
答案 1 :(得分:0)
找到了解决方法。希望这是最好的方式:
fd=nltk.FreqDist(brown.words(categories='news'))
sorted_fd = sorted(fd.items(), key=operator.itemgetter(1), reverse=True)
most_freq_words = [w for w,c in sorted_fd]
most_freq_words = most_freq_words[:10]
for word in most_freq_words:
print(word,':',fd[word])