如何在 python 中打印 Counter 的前十个元素

How to print the first ten elements from Counter in python

使用此代码,我打印了所有元素,这些元素首先按照文本文件中最常用的单词排序。但是我如何打印前十个元素?

with open("something.txt") as f:
    words = Counter(f.read().split())
print(words)

来自文档:

most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

我会尝试:

words = Counter(f.read().split()).most_common(10)

来源:here

这会给你 most common 十个字 words Counter:

first_ten_words = [word for word,cnt in words.most_common(10)]

您只需要从 Counter.most_common() 返回的 (word, count) 对列表中提取第一个元素:

>>> words.most_common(10)
[('qui', 4),
 ('quia', 4),
 ('ut', 3),
 ('eum', 2),
 ('aut', 2),
 ('vel', 2),
 ('sed', 2),
 ('et', 2),
 ('voluptas', 2),
 ('enim', 2)]

通过简单的列表理解:

>>> [word for word,cnt in words.most_common(10)]
['qui', 'quia', 'ut', 'eum', 'aut', 'vel', 'sed', 'et', 'voluptas', 'enim']