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?

you are probably not stripping punctuaztion from words.

You are choosing from the dictionary's values not the keys, and then using the values instead of a key for lookup

    while wordlimiter < 10:
        ## returns values linked to first_word
        next_word = random.choice(worddict[first_word])

you possibly want

        next_word = random.choice(worddict.keys())

        ##  or test for membership
        next_word=""
        while next_word not in worddict:
            next_word = random.choice(worddict[first_word])
            first_word = next_word

Also, we are assuming that lines 21 through 23 should all have the same indentation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.