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

From XPUB & Lens-Based wiki

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

abababbaa