diff --git a/.gitignore b/.gitignore index 1503dd9..34a5ae8 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -books/ \ No newline at end of file +books/ diff --git a/README.md b/README.md index 2a71b6e..25526ca 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # bookbot -BookBot is my first project! +BookBot is my first [Boot.dev](https://www.boot.dev) project! diff --git a/main.py b/main.py index 8ce665c..ba8b0d4 100644 --- a/main.py +++ b/main.py @@ -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 ") + 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() diff --git a/stats.py b/stats.py new file mode 100644 index 0000000..3385b7f --- /dev/null +++ b/stats.py @@ -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