如何在python中(但不是全部打印)中对单词频率进行排序



我必须使用python中的列表中的单词频率来计数,但是我想要的是我想根据它的发生来计算这些单词,但是我不想全部打印

在示例中,我有此列表

lists = ["me","sleep","love","me","love","love","love","rain","love","me","me","rain","book","book","rain","book","catch","watch"]

如果我使用此:

from collections import Counter
counts = Counter(lists)
print(counts)

它将结果:

Counter({'love': 5, 'me': 4, 'rain': 3, 'book': 3, 'sleep': 1, 'catch': 1, 'watch': 1})

,但我的预期结果是:

Sort by 4 words that have highest occurance
Love : 5
Me : 4
Rain : 3
Book : 3

so"睡眠","捕捉"one_answers"手表"将不包括在我的结果中我如何修改代码,以便我的代码像我的预期结果一样输出,我的意思是按具有最高值的XX单词进行排序。

非常感谢

from collections import Counter
counts = Counter(lists).most_common(4)
print ("Sort by 4 words that have highest occurance")
print ("n".join([str(x)+ " : " + str(y) for x,y in counts]))

输出:

Sort by 4 words that have highest occurance
love : 5
me : 4
rain : 3
book : 3
sleep : 1

如何修改代码,以便我的代码像我的预期结果一样输出

from collections import Counter

lists = ["me","sleep","love","me","love","love","love","rain","love",
         "me","me","rain","book","book","rain","book","catch","watch"]
counts = Counter(lists).most_common(4)
print ("Sort by 4 words that have highest occurance")
for word, count in counts:
    print("{} : {}".format(word.title(), count))

输出

Sort by 4 words that have highest occurance
Love : 5
Me : 4
Book : 3
Rain : 3

注意:尚无规则用于订购具有重复值的条目,例如BookRain

最新更新