User:Laura Macchini/prototyping/Soldier Soldier will you generate me

From XPUB & Lens-Based wiki
< User:Laura Macchini
Revision as of 00:29, 27 October 2011 by Laura Macchini (talk | contribs) (Created page with "== The Code == <source lang="python"> import random f = open ("soldier.txt", "r" ) s = f.read() words = s.split() nextwords = {} sCounter = 0 limit = 5 for (i,w) in enumerate(...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The Code

import random
 
f = open ("soldier.txt", "r" )
s = f.read()
words = s.split()
nextwords = {}
sCounter = 0
limit = 5

for (i,w) in enumerate(words):
	if i < len(words)-1:
		nword = words[i+1]
		if w in nextwords:
			nextwords[w].append(nword)
		else:
			nextwords[w] = []
			nextwords[w].append(nword)

first = random.choice(nextwords.items())

newList = []
newList.append(first[0].capitalize())
current = first[0]
 
while sCounter < limit:
	currentList = nextwords[current]
	next = random.choice(currentList)
	if next == ".":
			sCounter += 1
	newList.append(next)
	current = next

text = ""
punctuation = ['.',';',',','?','!',':']

for w in newList:
	if w in punctuation:
		if w == ".":
			text += w + "\n"
		else:
			text += w
	else:
		text += " " + w
print text

The Result