User:Lieven Van Speybroeck/Prototyping/6-Markov

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

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,