vendredi 6 octobre 2017

KeyError on the same word

I am trying to generate a sentence in the style of the bible. But whenever I run it, it stops at a KeyError on the same exact word. This is confusing as it is only using its own keys and it is the same word every time in the error, despite having random.choice.

This is the txt file if you want to run it: http://ift.tt/2y5IRxk

import random

files = []
content = ""
output = ""

words = {}

files = ["bible.txt"]
sentence_length = 200

for file in files:
    file = open(file)
    content = content + " " + file.read()

content = content.split(" ")

for i in range(100):  # I didn't want to go through every word in the bible, so I'm just going through 100 words
    words[content[i]] = []
    words[content[i]].append(content[i+1])

word = random.choice(list(words.keys()))

output = output + word

for i in range(int(sentence_length)):
    word = random.choice(words[word])
    output = output + word

print(output)




Aucun commentaire:

Enregistrer un commentaire