Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the first ten elements from Counter in python

Tags:

python

counter

With this code i print all the elements sorted with the most common word used in the textfile first. But how do i print the first ten elements?

with open("something.txt") as f:
    words = Counter(f.read().split())
print(words)
like image 674
Isac Avatar asked Oct 11 '17 15:10

Isac


1 Answers

From the docs:

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:

I would try:

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

Source: here

like image 72
FcoRodr Avatar answered Sep 23 '22 12:09

FcoRodr