User:Dusan Barok/Markov Chain

From XPUB & Lens-Based wiki
import random
from pprint import pprint

text = "he saw the black cat before she saw the red potato he hated ."
dictionary = {}
lastword = ""

for word in text.split():
    if lastword:
        if lastword not in dictionary:
            dictionary[lastword]=[]
        dictionary[lastword].append(word)
    lastword = word

pprint(dictionary)

word = "he"
while True:
    print word
    word = random.choice(dictionary[word])
    if word not in dictionary:
        break