User:Mirjam Dissel/Refrigerator
< User:Mirjam Dissel
Revision as of 11:26, 21 June 2011 by Mirjam Dissel (talk | contribs)
Markov chain haiku generator
#homework: look at new lines. it's like previous words (do i have previous word or not? that is new line!) store it in database.
#also, think about second order markov chain! database for sequences of two words. use tuples
import random, os, time
# one class to parse Haikus and build a Markov DB
class HaikuParser(object):
def __init__(self, markov_db):
self.db = markov_db
def parse(self, filename):
#import textfile
f = open(filename)
prev_word = None
#make words of textblock
for line in f:
if len(line.strip()):
for word in line.split():
if prev_word:
if prev_word in self.db:
self.db[prev_word].append(word)
else:
self.db[prev_word] = [word]
else:
if "<BEGIN>" in self.db:
self.db["<BEGIN>"].append(word)
else:
self.db["<BEGIN>"] = [word]
prev_word = word
else:
prev_word = None
f.close()
#loop through each word and put in dictionary: word as index and next word as value.
#if word exists, append next word to existing index
class HaikuMaker(object):
def __init__(self, markov_db):
self.db = markov_db
def make(self):
out = ""
num_words = random.randrange(9,12)
# take a <BEGIN> word
word = random.choice(self.db["<BEGIN>"])
for i in range(num_words):
out = out + word + " "
if word in self.db:
word = random.choice(self.db[word])
else:
#break
key = random.choice(self.db.keys())
word = random.choice(self.db[key])
return out.strip()
#choose index in dictionary (starting point), take value and look for value in dictionary.
#do the same: take this new index and take the value and see if it exist in the dictionary.
#print print print
if __name__ == "__main__":
#create dictionary
d = {}
hp = HaikuParser(d)
hp.parse("haiku.txt")
# not needed anymore
# print(hm.make())
# output image black font on white
for i in range(20):
hm = HaikuMaker(d)
thenewHaiku = hm.make()
i += 1
conv = "convert -background white -fill black -font Times-Roman -pointsize 50 -size 600x caption:'%s' haiku%s.gif" % (thenewHaiku, i)
os.system(conv)
time.sleep(0.50)