Skip to content

Commit 2f2e54c

Browse files
author
Karan Goel
committed
Count words done
1 parent 103b99d commit 2f2e54c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Text/count_words.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Count Words in a String - Counts the number of individual
3+
words in a string and display the top 5/10 most used words.
4+
"""
5+
6+
from collections import defaultdict
7+
import operator
8+
9+
if __name__ == '__main__':
10+
text = raw_input('Enter some text: \n')
11+
words = text.split() # very naive approach, split at space
12+
13+
counts = defaultdict(int) # no need to check existence of a key
14+
15+
# find count of each word
16+
for word in words:
17+
counts[word] += 1
18+
19+
# sort the dict by the count of each word, returns a tuple (word, count)
20+
sorted_counts = sorted(counts.iteritems(), \
21+
key=operator.itemgetter(1), \
22+
reverse=True)
23+
24+
# print top 5 words
25+
for (i, (word, count)) in enumerate(sorted_counts):
26+
if i < 5:
27+
print (word, count)

0 commit comments

Comments
 (0)