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 if __name__ == "__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