使用此代碼,我首先打印所有使用文本文件中使用的最常用詞語排序的元素。但是,我如何打印前十個元素?如何從python中的計數器打印前十個元素
with open("something.txt") as f:
words = Counter(f.read().split())
print(words)
使用此代碼,我首先打印所有使用文本文件中使用的最常用詞語排序的元素。但是,我如何打印前十個元素?如何從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