Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active March 1, 2019 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AO8/0bc989637dbc32c3d77356b438a9a1f2 to your computer and use it in GitHub Desktop.
Save AO8/0bc989637dbc32c3d77356b438a9a1f2 to your computer and use it in GitHub Desktop.
Another take on a simple word counter app with Python with some regex practice for good measure. Users enter a TXT file, specific a word to search, and the app returns the number of time that word occurs in the file
import re
from collections import Counter
def main():
print_header()
user_file = input("Enter the absolute path for your TXT file:\n\n")
print()
wc = get_word_counter(user_file)
print()
get_count_of_word(wc)
def print_header():
print("-".center(79, "-"))
print()
print(" Word Counter ".center(79))
print()
print("-".center(79, "-"))
print()
def get_word_counter(filename):
"""Opens a TXT file and returns a Counter object of words"""
with open(filename, "r", encoding="utf-8") as f:
words = re.findall(r"\w+", f.read().lower())
word_count = Counter(words)
return word_count
def get_count_of_word(counter_object):
"""Queries the Counter object for a specific word provided by the user"""
user_input = input("What word would you like to query?\n\n").lower()
print()
if user_input in counter_object:
print(f"The word '{user_input}' appears " \
f"{counter_object[user_input]} times " \
"in your TXT file.")
else:
print("The word you entered does not appear anywhere " \
"in your TXT file.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment