# 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(): word = word if word in word_counts: word_counts[word] += 1 # seen before else: word_counts[word] = 1 # never seen before return word_counts # Returns a list of (count, word) tuples of all words in the # given (word, count) dictionary that occur at least 2000 times. def most_common_words(word_counts): most_common = [] for (word, count) in word_counts.items(): if count > OCCURRENCES: most_common.append((count, word)) return most_common # Displays top words that occur most in the dictionary. def print_results(word_counts): wordlist = most_common_words(word_counts) wordlist.sort(reverse = True) for count, word in wordlist: 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()