User:Fako Berkers/Markovchain: Difference between revisions
Fako Berkers (talk | contribs) No edit summary |
Fako Berkers (talk | contribs) No edit summary |
||
(4 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
[[Category:Prototyping]] | |||
<source lang="python"> | <source lang="python"> | ||
text = "He saw the cat before he saw the potato." | text = "He saw the cat before he saw the potato." | ||
Line 14: | Line 15: | ||
prevword = word # remember previous word to write next word under current word | prevword = word # remember previous word to write next word under current word | ||
else: # Looped through entirely | |||
dic[word].append("EOF;") # Add end marker to last word | |||
print dic | print dic | ||
# Pop the words in memory | # Pop the words in memory in their original order. | ||
def readnorm(word): | def readnorm(word): | ||
if word != "EOF;": | |||
print word, | |||
if | |||
readnorm(dic[word].pop(0)) | readnorm(dic[word].pop(0)) | ||
Line 31: | Line 32: | ||
random.seed() | random.seed() | ||
# Print words in a random order ( | # Print words in a random order (but do not pop()) | ||
def readrand(word): | def readrand(word): | ||
if word != "EOF;": | |||
print word, | |||
if | |||
ind = random.randrange(len(dic[word])) | ind = random.randrange(len(dic[word])) | ||
readrand(dic[word][ind]) | readrand(dic[word][ind]) | ||
# Don't use recursion | |||
def readrandloop(): | |||
word = text.split()[0] | |||
while (word != "EOF;"): | |||
print word, | |||
ind = random.randrange(len(dic[word])) # Get index for new random word | |||
word = dic[word][ind] | |||
# Print output. | |||
print "Random version: ", | |||
readrandloop() | |||
print | print | ||
print "Normal version: ", | |||
readnorm("He") | readnorm("He") | ||
</source> | </source> | ||
Latest revision as of 20:39, 26 April 2011
text = "He saw the cat before he saw the potato."
dic = {}
prevword = ''
# Read the text into memory.
for word in text.split():
if prevword != '': # doesn't occur the first time
dic[prevword].append(word) # write current word under previous word in dic
if word not in dic:
dic[word] = [] # create word in dic
prevword = word # remember previous word to write next word under current word
else: # Looped through entirely
dic[word].append("EOF;") # Add end marker to last word
print dic
# Pop the words in memory in their original order.
def readnorm(word):
if word != "EOF;":
print word,
readnorm(dic[word].pop(0))
# Start random generator
import random
random.seed()
# Print words in a random order (but do not pop())
def readrand(word):
if word != "EOF;":
print word,
ind = random.randrange(len(dic[word]))
readrand(dic[word][ind])
# Don't use recursion
def readrandloop():
word = text.split()[0]
while (word != "EOF;"):
print word,
ind = random.randrange(len(dic[word])) # Get index for new random word
word = dic[word][ind]
# Print output.
print "Random version: ",
readrandloop()
print
print "Normal version: ",
readnorm("He")