Skip to main content
 首页 » 编程设计

python之同一个词的KeyError

2024年10月01日852php

我正在尝试生成圣经风格的句子。但是每当我运行它时,它都会在同一个单词上的 KeyError 处停止。这是令人困惑的,因为它只使用自己的键,并且每次在错误中都是同一个词,尽管有 random.choice。

如果您想运行它,这是 txt 文件:ftp://ftp.cs.princeton.edu/pub/cs226/textfiles/bible.txt

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) 

请您参考如下方法:

KeyError 发生在这一行:

word = random.choice(words[word]) 

它总是发生在“中间”这个词上。

如何? “中间”是文本中的第 100 个单词。 而第100位是第一次见到。 结果是“midst”本身从未作为关键字放入 words 中。 因此 KeyError。

为什么程序到达这个词这么快?部分原因是这里有一个错误:

for i in range(100): 
    words[content[i]] = [] 
    words[content[i]].append(content[i+1]) 

这里的错误是 words[content[i]] = [] 语句。 每次看到一个字, 您为它重新创建一个空列表。 而“midth”之前的词是“the”。 很常见的一句话, 文中很多其他词都有“the”。 由于 words["the"] 是 ["midst"], 尽管存在随机性,但问题往往会发生很多次。

您可以修复创建单词的错误:

for i in range(100): 
    if content[i] not in words: 
        words[content[i]] = [] 
    words[content[i]].append(content[i+1]) 

然后当你随机选择单词时, 我建议添加一个 if word in words 条件, 处理输入中最后一个单词的极端情况。