# This program reads an input file of thesaurus data # and allows the user to look up synonyms for words. # It stores words in a nested dictionary of lists, # where each key is a word and its value is a list # of synonyms of that word from the thesaurus file. import random # Reads the given input file and converts its data # into a dictionary where each key is a word and each # value is a list of synonyms for that word. def read_thesaurus(filename): thesaurus = {} with open(filename) as file: lines = file.readlines() for i in range(0, len(lines) - 3, 4): word = lines[i].strip() synonyms = lines[i + 2].strip().split("|") thesaurus[word] = synonyms return thesaurus # Looks up and prints a randomly chosen synonym # for the given word in the given thesaurus. # If the word is not found, prints an error message. def find_random_synonym(thesaurus, word): if word in thesaurus: synonyms = thesaurus[word] syn = random.choice(synonyms) print("A synonym for", word, "is", syn) else: print(word, "not found.") def main(): # introduction print("This program looks up random synonyms") print("for you from a thesaurus.") print() # read thesaurus into a dictionary thesaurus = read_thesaurus("thesaurus.txt") # look up random synonyms word = input("Word to look up (Enter to quit)? ") while word != "": find_random_synonym(thesaurus, word) word = input("Word to look up (Enter to quit)? ") print("Goodbye.") main()