'''Program to print out a word count dictionary for a given file.''' import re FILENAME_PROMPT = 'Enter filename: ' WORD_MATCHER = '[a-zA-Z]+' def extract_words(gizmo): '''Returns a list of all the words contained in filename.''' input_file = open(gizmo, 'r') source_string = input_file.read().lower() input_file.close() words = re.findall(WORD_MATCHER, source_string) return words def build_word_dict(word_list): '''Constructs and returns a dictionary of words in word_list to their occurrence counts.''' word_dict = {} for word in word_list: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 return word_dict def print_dictionary(dict_to_print): '''Print out the contents of the given word count dictionary in alphabetical order.''' for word, count in sorted(dict_to_print.items()): print("Word '{0}' appeared {1} times".format(word, count)) def main(): '''Ask for a filename, then construct and print out a listing of the number of occurrences of each word in the filename.''' filename_to_read = input(FILENAME_PROMPT) words_in_file = extract_words(filename_to_read) constructed_dict = build_word_dict(words_in_file) print_dictionary(constructed_dict) main()