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

2
.gitignore vendored
View File

@@ -1 +1 @@
books/
books/

View File

@@ -1,3 +1,3 @@
# bookbot
BookBot is my first project!
BookBot is my first [Boot.dev](https://www.boot.dev) project!

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()

26
stats.py Normal file
View File

@@ -0,0 +1,26 @@
def get_num_words(text):
words = text.split()
return len(words)
def get_chars_dict(text):
chars = {}
for c in text:
lowered = c.lower()
if lowered in chars:
chars[lowered] += 1
else:
chars[lowered] = 1
return chars
def sort_on(d):
return d["num"]
def chars_dict_to_sorted_list(num_chars_dict):
sorted_list = []
for ch in num_chars_dict:
sorted_list.append({"char": ch, "num": num_chars_dict[ch]})
sorted_list.sort(reverse=True, key=sort_on)
return sorted_list