User:Lieven Van Speybroeck/Prototyping/6-Markov

From XPUB & Lens-Based wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Still trying out some code...

import random

text = "This is a text that is a test to test the text in a test"

words = text.split()
nextwords = {}
i = 0

for w in words:
	print w
	# for all items stored in words
	if i < len(words)-1:
		nextword = words[i+1]
		# if there's already a dictionary of nextwords for the word, append the new 'nextword' to that dictionary
		if w in nextwords:
			nextwords[w].append(nextword)
		# if there's no dictionary of nextwords for the word yet, make one and append the first 'nextword'	
		else:
			nextwords[w] = []
			nextwords[w].append(nextword)
		print nextwords[w]
		i+=1

newtext = []
focus = random.choice(nextwords.keys())
	
for w in words:
	randnextw = random.choice(nextwords[focus])
	newtext.append(randnextw)
	focus = randnextw
	
for w in newtext:
	print w,