import random

def open_text_file():
    '''Return an open file specified by the user.'''
    
    filename = raw_input("Please enter a text file name: ")
    return open(filename)

def identify_words(f):
    '''Return a dictionary containing words from the file f as 
    keys and a list of the words that follow them as values.'''
    
    word_dict = {}      # string -> [string]
    preceding = ''
    
    for line in f:
        words = line.strip().split()
        for word in words:
            pre_list = word_dict.setdefault(preceding, [])
            pre_list.append(word)
            
            preceding = word
       
    return word_dict

def mimic_text(word_dict, length):
    '''Return a made-up story of the specified length using 
    the words and contexts in the dictionary word_dict.'''
    
    story = ""
    current_word = ""

    for i in range(length):
        # Pick a random word that follows the current word
        word = pick_random(word_dict, current_word)
        story += " " + word
        current_word = word
      
    return story

def pick_random(word_dict, word):
    '''Select a random word from the list associated with it 
    in the dictionary.'''
    
    word_list = word_dict.get(word)
    random.shuffle(word_list)
    return word_list[0]
    

if __name__ == "__main__":
    f = open_text_file()
        
    words = identify_words(f)
    print mimic_text(words, 20)
    