-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
43 lines (33 loc) · 1.28 KB
/
main.py
File metadata and controls
43 lines (33 loc) · 1.28 KB
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
import sys
from stats import get_num_words
def main():
if len(sys.argv) != 2:
print("Usage: python3 main.py <path_to_book>")
sys.exit(1)
book_path = sys.argv[1]
text = get_book_text(book_path)
num_words = get_num_words(text)
found_letters = get_num_unique_characters(text)
sorted_letters = sort_letters_by_frequency(found_letters)
# Print character frequencies
for letter, count in sorted_letters:
print(f"{letter}: {count}")
def get_book_text(path):
with open(path) as f:
return f.read()
def get_num_unique_characters(text):
found_letters = {}
for character in text.lower():
if character.isalpha():
found_letters[character] = found_letters.get(character, 0) + 1
return found_letters
def write_report(num_words_found, sorted_found_letters):
print("--- Begin report of books/frankenstein.txt ---")
print(f"{num_words_found} words found in the document")
print("")
for letter, count in sorted_found_letters:
print(f"The '{letter}' character was found {count} times")
print("--- End report ---")
def sort_letters_by_frequency(found_letters):
return sorted(found_letters.items(), key=lambda x: x[1], reverse=True)
main()