[英]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])
返回n個最常見元素及其計數的列表,從最常見到最少。 如果省略n或None,則most_common()返回計數器中的所有元素。 具有相同計數的元素是任意排序的:
我會嘗試:
words = Counter(f.read().split()).most_common(10)
來源: 這里
這將為您提供單詞中最常見的十個words
Counter
:
first_ten_words = [word for word,cnt in words.most_common(10)]
您只需要從Counter.most_common()
返回的對(word, count)
list (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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.