From f0a53dbf74b89f2be7de4360dfd1f67e50134343 Mon Sep 17 00:00:00 2001 From: franky212 Date: Wed, 23 Oct 2024 10:46:59 -0600 Subject: [PATCH] Adding in character counting/reporting functionality --- .gitignore | 2 ++ main.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 .gitignore create mode 100644 main.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a16814 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.venv +books/ \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..153e9c7 --- /dev/null +++ b/main.py @@ -0,0 +1,38 @@ +def main(): + with open("./books/frankenstein.txt", 'r') as f: + file_contents = f.read() + count = count_words(file_contents) + print("--- Begin report of books/frankenstein.txt ---") + print(f"{count} words found in the document\n") + character_count(file_contents) + print("\n--- End report ---") + f.close() + +def count_words(text): + words = text.split() + return len(words) + +def character_count(text): + characters = {} + for word in text: + lowercased_word = word.lower() + for character in lowercased_word: + if character.isalpha(): + if character in characters: + characters[character] += 1 + else: + characters[character] = 1 + character_list = [] + for character in characters: + character_list.append({"character": character, "num": characters[character]}) + character_list.sort(reverse=True, key=sort_on) + report(character_list) + +def sort_on(dict): + return dict["num"] + +def report(character_list): + for dict in character_list: + print(f"The '{dict["character"]}' character was found {dict["num"]}") + +main() \ No newline at end of file