forked from jmelahman/python-for-everybody-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise10_3.py
47 lines (40 loc) · 1.69 KB
/
exercise10_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
37
38
39
40
41
42
43
44
45
46
47
"""
Exercise 10.3: Write a program that reads a file and prints the letters in
decreasing order of frequency. Your program should convert all the input to
lower case and only count the letters a-z. Your program should not count
spaces, digits, puntuaction, or anything other than letters a-z. Find text
samples from several different languages and see how letter frequency varies
between languages. Compare your results with the tables at
wikipedia.org/wiki/Letter_frequencies
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, June 1, 2017
"""
import string
counts = 0
dictionary_counts = dict() #Initializes the dictionary
fname = input('Enter file name: ')
try:
fhand = open(fname)
except:
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 then punctuation, and lower cases the letters
words = line.split()
for word in words:
for letter in word:
counts += 1 #counts each letter for relative frequencies
if letter not in dictionary_counts:
dictionary_counts[letter] = 1
else:
dictionary_counts[letter] += 1
relative_lst = list() #Initializes the list
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)