User:Amy Suo Wu/markov chains

From XPUB & Lens-Based wiki

[markov chains] [poetry generators]


the dog hacked my homework

text: he saw the cat before he saw the potato.

#!/usr/bin/env.python
import random
#random library

# manually building the dictionary with {}
nextwords = {'he': ['saw'], 'saw': ['the'], 'the': ['cat','potato'], 'cat': ['before'], 'before': ['he'], 'potato': ['.']}

# assigning the item variable from the dictionary. e.g 'he' 
focus = 'he'
# call the next words for what ever is stored in the variable focus variable
print nextwords[focus]

#next step is to get him to pick a random word from the values list in the dictionary. build a loop, start anywhere and assign it to variable (focus),
#then search value accordingly and pick out a random word from the value. Then assign the value that he finds to the variable [focus]. jumping to
 #the next and then calling it focus. *still missing: storing what is finds in a list* 



#dict(one=1, two=2)
#dict({'one': 1, 'two': 2})
#dict(zip(('one', 'two'), (1, 2)))
#dict([['two', 2], ['one', 1]])

text: she sells sea shells by the sea shore.

import random

nextwords = {
    'she': ['sells'],
    'sells': ['sea'],
    'sea': ['shells','shore'],
    'shells': ['by'], 
    'by': ['the'], 
    'the': ['sea'],
    'shore': ['.']
}


word = 'sea'

while True: 
#simple loop

    print word

#    print random.choice(nextwords['she']) 
    if word == '.':
        break 
    word = random.choice(nextwords[word])