Advertisement
Guest User

Markov Chain text generator in Python

a guest
Oct 1st, 2012
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import random
  2. def create_chain_arr_lines(lines):
  3.     markov_chain = {}
  4.     hasPrev = False
  5.     for line in lines:
  6.         for currWord in line.split():
  7.             if currWord != '':
  8.                 currWord = currWord.lower()
  9.                 if hasPrev == False:
  10.                     prevWord = currWord
  11.                     hasPrev = True
  12.                 else:
  13.                     markov_chain.setdefault(prevWord, []).append(currWord)
  14.                     prevWord = currWord
  15.     return markov_chain
  16.  
  17. def construct_sentence(markov_chain):
  18.     while True:
  19.         word = random.choice(markov_chain.keys())
  20.         if word[-1] not in ('.','?'):
  21.             break
  22.     generated_sentence = word.capitalize()
  23.     while word[-1] not in ('.','?'):
  24.         newword = random.choice(markov_chain[word])
  25.         generated_sentence += ' '+newword
  26.         word = newword #TODO fix possible crash if this is not a key (last word parsed)
  27.     return generated_sentence
  28.  
  29. #example usage
  30. mc = create_chain_arr_lines(open('someLargeText.txt'))
  31.  
  32. #Generate 20 phrases
  33. for i in xrange(0, 20):
  34.     print construct_sentence(mc)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement