-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathword_counter.py
More file actions
36 lines (30 loc) · 797 Bytes
/
word_counter.py
File metadata and controls
36 lines (30 loc) · 797 Bytes
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
27
28
29
30
31
32
33
34
35
36
import re
def word_counter(fname):
wc = {}
try:
f = open(fname, "r", encoding="utf-8")
lines = f.readlines()
for line in lines:
wd = line.split(" ")
for i in wd:
j = i.strip("\n")
j = j.lower()
j = re.sub("[^a-zA-Z\s]", "", j)
if j == "":
continue
if j in wc:
wc[j] += 1
else:
wc[j] = 1
except FileNotFoundError:
print("File not found")
return
except Exception as e:
print(e)
return
finally:
f.close()
return wc
wc = word_counter("file_name.txt")
wc2 = dict(sorted(wc.items(), key=lambda x: x[1], reverse=True))
print(wc2)