File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments