title: text generation in Python
body: <p>I am a beginner in Python and I am using Python 2.7. I started work on a project that generate text by using Markov chain. I applied <a href="https://pythonadventures.wordpress.com/tag/text-generator/" rel="nofollow noreferrer">this</a> with some modifications. </p>
  
  <pre><code>#!/usr/bin/env 
  # encoding: utf-8
  
  
  from pprint import pprint
  from random import choice
  
  #----------------------build dictionary--------------------------
  EOS = ['.', '?', '!']
  fname=open(r'C:\Python27\nujudfile.txt', 'r')
  text = fname.read()
  words = text.split()
  d = {}
  for i, word in enumerate(words):
      try:
          first, second, third = words[i], words[i+1], words[i+2]
      except IndexError:
          break
      key = (first, second)
  
      if key not in d:
           d[key] = []
          #
  d[key].append(third)
  pprint(d)
  #-------------------------generate text---------------------------
  li = []
  first, second = key
  li.append(first)
  li.append(second)
  while True:
      try:
          third = choice(d[key]) 
      except KeyError:
          break
      li.append (second)
      li.append(third)
      if third[-1] in EOS: 
          break
      # else
      key = (second, third)
      first, second = key
  
  gtext= ' '.join(li)
  print gtext
  </code></pre>
  
  <p>my problem is when I run the code it always generates the last three words from the input file. I want it to generate new text randomly.</p>