-
Notifications
You must be signed in to change notification settings - Fork 4
/
day3-activity-3.py
36 lines (29 loc) · 1.1 KB
/
day3-activity-3.py
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 string
counts = 0 # Initialize variables
dictionary_counts = dict()
relative_lst = list()
fname = input('Enter file name: ')
try:
fhand = open(fname)
except FileNotFoundError:
print('File cannot be opened:', fname)
exit()
for line in fhand:
line = line.translate(str.maketrans('', '', string.digits))
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
# Removes numbers and punctuation then sets all letters to lower case
words = line.split()
for word in words:
for letter in word:
# Count each letter for relative frequencies
counts += 1
if letter not in dictionary_counts:
dictionary_counts[letter] = 1
else:
dictionary_counts[letter] += 1
for key, val in list(dictionary_counts.items()):
relative_lst.append((val / counts, key)) # Computes the relative frequency
relative_lst.sort(reverse=True) # Sorts from highest rel freq
for key, val in relative_lst:
print(key, val)