import random
foundwords = []
wordsDict = {}
#opens file and creates array words with all words as a seperate string item
with open("text", "r") as file:
words = file.read().replace('\n',' ').split(' ')
#puts the words after all occurances of word in the list foundwords and returns it (read the code, it makes more sense than how I explain it)
def findwords(word):
for g in range(len(words) - 1):
if words[g] == word:
if not words[g + 1] == '':
foundwords.append(words[g + 1].lower())
return foundwords
#uses the previous function on all words in the sample text and adds the list foundwords as a value with the word as a key
for i in range(len(words) - 1):
foundwords = findwords(words[i])
wordsDict.setdefault(words[i], foundwords)
del foundwords[:]
#chooses a random word from the foundwords list and returns it
def nextword(word):
wordList = wordsDict[word]
new = wordList[random.choice(wordList)]
return new
#this is the function that runs. it creates the final list with a random word and calls the function above with that random word.
def assemble():
final = [random.choice(words).capitalize()]
final.append(nextword(final[-1]).lower())
print(final)
assemble()
I'm in need of help on this project again!
This is a markov chain project. Each paragraph has a seperate function and I've labelled each of them.
I'm currently getting a KeyError that looks like this:
Traceback (most recent call last):
File "main.py", line 31, in <module>
assemble()
File "main.py", line 28, in assemble
final.append(nextword(final[-1]).lower())
File "main.py", line 22, in nextword
wordList = wordsDict[word]
KeyError: 'He' #<-- or whatever random word was chosen
I've concluded that the foundwords list is empty. The thing is that they are filled in the foundwords function and the for loop, but the lists are empty in the dictionary when called in the nextword function. How can I fix this problem?
I'm a beginner programmer, so if my code is inefficient, that's why. Please feel free to correct me, feedback is appreciated!