File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #-*-coding:utf-8-*-
2+ import os
3+ import re
4+
5+ def word_statistics (filePath ):
6+ wordDict = {}
7+ with open (filePath ,'rt' ) as f :
8+ for line in f :
9+ words = re .split ('[,.\s]\s*' ,line )
10+ for word in words :
11+ if word .lower () in wordDict and word .isalpha ():
12+ wordDict [word .lower ()] += 1
13+ elif word .lower () not in wordDict and word .isalpha ():
14+ wordDict [word .lower ()] = 1
15+
16+ wordSorted = sorted (zip (wordDict .keys (),wordDict .values ()))
17+
18+ for word ,count in wordSorted :
19+ print (word ,':' ,count )
20+
21+ if __name__ == '__main__' :
22+ word_statistics (r'...\test.txt' )
23+
24+ #output:
25+ # a : 11
26+ # about : 1
27+ # access : 1
28+ # algorithm : 1
29+ # allowing : 3
30+ # allowingwith : 1
31+ # alone : 4
32+ # an : 2
33+ # and : 1
34+ # anything : 1
35+ # are : 1
36+ # as : 3
37+ # attribute : 1
38+ # attributes : 6
39+ # calling : 1
40+ # calls : 1
41+ # can : 6
42+ # case : 1
43+ # change : 1
44+ # class : 4
45+ # code : 5
46+ # complicated : 4
47+ # control : 1
48+ # creates : 1
49+ # defining : 1
50+ # definition : 1
51+ # do : 4
52+ # drive : 1
53+ # easily : 1
54+ # easy : 5
55+ # etc : 1
56+ # everything : 4
57+ # expose : 1
58+ # extra : 2
59+ # fact : 1
60+ # fall : 4
61+ # for : 6
62+ # forget : 1
63+ # function : 6
64+ # functions : 4
65+ # generator : 8
66+ # generators : 4
67+ # going : 1
68+ # history : 1
69+ # how : 1
70+ # however : 1
71+ # if : 7
72+ # implement : 1
73+ # in : 6
74+ # instance : 1
75+ # interact : 5
76+ # internal : 1
77+ # into : 4
78+ # is : 6
79+ # it : 9
80+ # iteration : 1
81+ # just : 1
82+ # lead : 4
83+ # like : 1
84+ # loop : 1
85+ # makes : 1
86+ # method : 5
87+ # methods : 1
88+ # might : 1
89+ # needs : 4
90+ # normal : 1
91+ # of : 10
92+ # one : 1
93+ # or : 1
94+ # other : 5
95+ # part : 1
96+ # parts : 4
97+ # potential : 1
98+ # program : 4
99+ # provide : 1
100+ # putting : 1
101+ # rather : 4
102+ # require : 1
103+ # shown : 2
104+ # since : 1
105+ # solution : 1
106+ # state : 1
107+ # step : 1
108+ # subtlety : 1
109+ # such : 1
110+ # technique : 1
111+ # than : 1
112+ # that : 3
113+ # the : 13
114+ # this : 6
115+ # to : 22
116+ # trap : 4
117+ # treat : 1
118+ # trying : 4
119+ # unusual : 4
120+ # use : 2
121+ # user : 1
122+ # users : 1
123+ # using : 1
124+ # via : 1
125+ # want : 1
126+ # ways : 4
127+ # with : 13
128+ # would : 1
129+ # write : 1
130+ # you : 7
131+ # your : 6
You can’t perform that action at this time.
0 commit comments