Skip to content

Instantly share code, notes, and snippets.

@Averroes
Created April 10, 2015 14:05
Show Gist options
  • Save Averroes/6383d3affe933ad79e64 to your computer and use it in GitHub Desktop.
Save Averroes/6383d3affe933ad79e64 to your computer and use it in GitHub Desktop.
determine the top n items occurring in a list
# example.py
#
# Determine the most common words in a list
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# outputs [('eyes', 8), ('the', 5), ('look', 4)]
# Example of merging in more words
morewords = ['why','are','you','not','looking','in','my','eyes']
word_counts.update(morewords)
print(word_counts.most_common(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment