# File wannabe_starter2.py.txt import random def build_dict(r): '''Return a dictionary where the keys are words in reader r and the value for a key is the list of words that were found to follow the key.''' # word_dict: word -> list of words that follow word last_word = "" word_dict = {} for line in r: words = line.split() for w in words: if last_word in word_dict: word_dict[last_word].append(w) else: word_dict[last_word] = [w] last_word = w # Take care of the special case of the very last word # only appearing once - at the end of the file if not last_word in word_dict: word_dict[last_word] = [""] return word_dict def write_epic(word_dict, num_words): '''Based on the word_table dictionary, produce an epic of num_words words.''' epic = '' current_word = "" for i in range(num_words): values = word_dict[current_word] # get words that follow current word random.shuffle(values) new_word = values[0] epic += new_word + " " current_word = new_word return epic def main(): filename = "simple.txt" infile = open(filename) table = build_dict(infile) infile.close() infile = open(filename) for line in infile: print(line) print("") print(table) epic = write_epic(table,7) print("Now, let's see our epic") print(epic) main()