-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
45 lines (34 loc) · 1.03 KB
/
main.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
def main():
book_path = "books/frankenstein.txt"
print(f"--- Begin report of {book_path} ---")
text = get_text(book_path)
count = count_words(text)
print(f"{count} words found in the document.\n")
letters = sort_letters(text)
for items in letters:
print(f"The '{items['letter']}' character was found {items['count']} times")
print("--- End report ---")
def get_text(book_path):
with open(book_path) as file:
text = file.read()
return text
def count_words(text):
words = text.split()
return len(words)
def sort_on(dict):
return dict["count"]
def sort_letters(text):
result = []
chars_dict = {}
lowered = text.lower()
for letter in lowered:
if letter.isalpha():
if letter in chars_dict:
chars_dict[letter] += 1
else:
chars_dict[letter] = 1
for ch in chars_dict:
result.append({"letter": ch, "count": chars_dict[ch]})
result.sort(reverse=True, key=sort_on)
return result
main()