# Uses a dictionary to implement a word count, # so that the user can see which words # occur the most in the book Moby-Dick. # minimum number of occurrences needed to be printed OCCURRENCES = 2000 def intro(): print("This program displays the most") print("frequently occurring words from") print("the book Moby Dick.") print() # Reads book and returns a dictionary of (word, count) pairs. def count_all_words(file): # read the book into a dictionary word_counts = {} for word in file.read().lower().split(): if word in word_counts: word_counts[word] += 1 # seen before else: word_counts[word] = 1 # never seen before return word_counts # Displays top words that occur in the dictionary # at least OCCURRENCES number of times. def print_results(word_counts): for word, count in word_counts.items(): if count > OCCURRENCES: print(word, "occurs", count, "times.") def main(): intro() with open("mobydick.txt") as file: word_counts = count_all_words(file) print_results(word_counts) main()