forked from karan/Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_words.py
26 lines (20 loc) · 815 Bytes
/
count_words.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
Count Words in a String - Counts the number of individual
words in a string and display the top 5/10 most used words.
"""
from collections import defaultdict
import operator
if __name__ == '__main__':
text = raw_input('Enter some text: \n')
words = text.split() # very naive approach, split at space
counts = defaultdict(int) # no need to check existence of a key
# find count of each word
for word in words:
counts[word] += 1
# sort the dict by the count of each word, returns a tuple (word, count)
sorted_counts = sorted(counts.iteritems(), \
key=operator.itemgetter(1), \
reverse=True)
# print top 5 words
for (word,count) in sorted_counts[:5]: # thanks @jrwren for this!
print (word, count)