I have been learning Python for a month now and just finished coding my first Markov chain.
def markovmaker(filename):
import random
fhin = open(filename, 'r')
worddict = {}
newlist = []
wordlimiter = 0
for line in fhin:
wordlist = line.split()
for word in wordlist[:-1]:
pos = wordlist.index(word)
if word in worddict:
if wordlist[pos+1] not in worddict[word]:
worddict[word].append(wordlist[pos+1])
else:
pass
else:
worddict[word] = [wordlist[pos+1]]
first_word = random.choice(worddict.keys())
newlist.append(first_word)
while wordlimiter < 10:
next_word = random.choice(worddict[first_word])
newlist.append(next_word)
first_word = next_word
wordlimiter += 1
print ' '.join(newlist)
Sometimes the script works fine. But, other times, it displays a key error.
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
markovmaker('D:/rgumnt.txt')
File "<pyshell#35>", line 20, in markovmaker
next_word = random.choice(worddict[first_word])
KeyError: 'still,'
The word is 'still,' here but it changes each time. Can someone please tell me what I am doing wrong? Also, is there a way I can simplify the code?