如何从python中的计数器打印前十个元素
问题描述:
使用此代码,我首先打印所有使用文本文件中使用的最常用词语排序的元素。但是,我如何打印前十个元素?如何从python中的计数器打印前十个元素
with open("something.txt") as f:
words = Counter(f.read().split())
print(words)
答
从文档:
most_common([N])
返回到至少n个最常见的元素和从所述最常见的其计数的列表。如果省略n或None,most_common()返回计数器中的所有元素。以同样罪名元素任意订制:
我会尝试:
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)]
您只需要提取第一个e
>>> 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']
从对
(word, count)
名单由
Counter.most_common()
返回lements