0

我正在尝试运行一个 python 程序,该程序可以从一个文件中运行一个字典,其中包含一个单词列表,每个单词都有一个分数和标准差。我的程序如下所示:

theFile = open('word-happiness.csv', 'r')

theFile.close()



def make_happiness_table(filename):
   ''' make_happiness_table: string -> dict
       creates a dictionary of happiness scores from the given file '''

return {}


make_happiness_table("word-happiness.csv")

table = make_happiness_table("word-happiness.csv")
(score, stddev) = table['hunger']
print("the score for 'hunger' is %f" % score)

我的文件中有“饥饿”一词,但是当我运行该程序以获取“饥饿”并返回其给定分数和标准偏差时,我得到:

(score, stddev) = table['hunger']
KeyError: 'hunger'

即使字典中有“饥饿”,我怎么会得到一个关键错误?

4

1 回答 1

1

"hunger"不在字典中(这就是KeyError告诉你的)。问题可能是你的make_happiness_table功能。我不知道你是否发布了完整的代码,但这并不重要。在函数结束时,无论函数内部发生了什么,都返回一个空字典( )。{}

您可能想在该函数中打开文件,创建字典并返回它。例如,如果您的 csv 文件只有 2 列(用逗号分隔),您可以这样做:

def make_happiness_table(filename):
    with open(filename) as f:
         d = dict( line.split(',') for line in f )
         #Alternative if you find it more easy to understand
         #d = {}
         #for line in f:
         #    key,value = line.split(',')
         #    d[key] = value
    return d
于 2012-10-18T14:21:53.323 回答