File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+ import click
3+
4+
5+ @click .command ()
6+ @click .argument ("path" , type = click .Path (exists = True ))
7+ def main (path ):
8+ """
9+ Count the number of times each word appears in a file and print 10 most common.
10+ """
11+ delimiters = ". , ; : ? $ @ ^ < > # % ` ! * - = ( ) [ ] { } / \" '" .split ()
12+ counts = defaultdict (int )
13+
14+ for line in open (path , "r" ).readlines ():
15+
16+ # replace all delimiters with spaces
17+ for delimiter in delimiters :
18+ line = line .replace (delimiter , " " )
19+
20+ # split the lowercased line into words and increase count
21+ for word in line .lower ().split ():
22+ counts [word ] += 1
23+
24+ # print 10 most common words
25+ for word , count in sorted (counts .items (), key = lambda x : x [1 ], reverse = True )[:10 ]:
26+ print (word , count )
27+
28+
29+ if __name__ == "__main__" :
30+ main ()
You can’t perform that action at this time.
0 commit comments