python3.6 KeyError: 'Called' 问题。

m0_38101400 2018-01-25 03:26:57
python 3.6 报错,百度不清楚问题。


from random import randint
from urllib.request import urlopen


def wordListSum(word_list):
sum_int = 0
for word, value in word_list:
sum_int += value
return sum_int


def retrieveRandomWord(wordList):
rand_index = randint(1, wordListSum(wordList))
for word, value in wordList:
rand_index -= value
if rand_index <= 0:
return word


def buildWordDict(text_str):
# 剔除换行号和引号
text_str = text_str.replace("\n", " ")
text_str = text_str.replace("\"", "")

punctuation = [',', '.', ';', ':']
for symbol in punctuation:
text_str = text_str.replace(symbol, " " + symbol + " ")

words = text_str.split(" ")
# 过滤空单词
words = [word for word in words if word != ""]
word_dicts = {}
for no in range(1, len(words)):
if words[no - 1] not in word_dicts[words[no - 1]]:
word_dicts[words[no - 1]][words[no]] = 0
word_dicts[words[no - 1]][words[no]] += 1
return word_dicts


text = str(urlopen("http://pythonscraping.com/files/inaugurationSpeech.txt"
"").read(), 'utf-8')
word_dict = buildWordDict(text)

# 生成链长为100的马尔科夫链
length = 100
chain = ""
currentWord = "I"
for i in range(0, length):
chain += currentWord + " "
currentWord = retrieveRandomWord(word_dict[currentWord])

print(chain)


报错
Traceback (most recent call last):
File "D:/gitDocument/document/WebScrapingWithPython/markovChain.py", line 42, in <module>
word_dict = buildWordDict(text)
File "D:/gitDocument/document/WebScrapingWithPython/markovChain.py", line 34, in buildWordDict
if words[no - 1] not in word_dicts[words[no - 1]]:
KeyError: 'Called'


...全文
499 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
oyljerry 2018-01-25
  • 打赏
  • 举报
回复
字典中有没有这个Called 键值 可以先打印一下看看

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧