我试图运行一个python程序,该程序可以从文件中运行字典列表,每个单词赋予一个分数和标准差。我的计划是这样的:TAB break在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'''
with open(filename) as f:
d = dict(line.split(' ') for line in f)
return d
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)
我的.csv文件的格式为
word{TAB}score{TAB}standard_deviation
,我试图创造这样的字典。我如何创建这样一本词典,以便我可以从函数中打印出“饥饿”这样的词,并获得它的分数和偏差?
如果字段之间由TAB分隔,那么它不是真正的“CSV”(“逗号分隔值”),是吗?如果它实际上是用逗号分开的,你可以使用csvreader类来处理把csv转换成字典的过程 – mfrankli
@mfrankli你可以使用csvreader读取由任何字符分隔的文件,这个选项对于那个有趣的 –
啊,从来不知道那!虽然有意义(在这种情况下,这将是这个应用程序的最佳选择,我想象一下吗?) – mfrankli