This commit is contained in:
2025-02-22 19:49:06 +02:00
parent ad5c97a011
commit 2ad031eee9
4 changed files with 63 additions and 19 deletions

52
main.py
View File

@@ -1,23 +1,41 @@
chars = {}
filename = 'books/frankenstein.txt'
import sys
from stats import (
get_num_words,
chars_dict_to_sorted_list,
get_chars_dict,
)
with open(filename) as f:
print(f"--- Begin report of {filename} ---")
file_contents = f.read()
words = len(file_contents.split())
print(f"{words} words found in the document\n")
def main():
if len(sys.argv) < 2:
print("Usage: python main.py <path_to_book>")
sys.exit(1)
book_path = sys.argv[1]
for char in file_contents:
lower = char.lower()
if 'a' <= lower and lower >= '<':
if lower not in chars:
chars[lower] = 0
chars[lower] += 1
text = get_book_text(book_path)
num_words = get_num_words(text)
chars_dict = get_chars_dict(text)
chars_sorted_list = chars_dict_to_sorted_list(chars_dict)
print_report(book_path, num_words, chars_sorted_list)
sorted_dict = dict(sorted(chars.items(), key=lambda item: item[1], reverse=True))
for char in sorted_dict:
print(f"The '{char}' character was found {chars[char]} times")
def get_book_text(path):
with open(path) as f:
return f.read()
print('--- End report ---')
def print_report(book_path, num_words, chars_sorted_list):
print("============ BOOKBOT ============")
print(f"Analyzing book found at {book_path}...")
print("----------- Word Count ----------")
print(f"Found {num_words} total words")
print("--------- Character Count -------")
for item in chars_sorted_list:
if not item["char"].isalpha():
continue
print(f"{item['char']}: {item['num']}")
print("============= END ===============")
main()