I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
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)
My .csv file is in the form
word{TAB}score{TAB}standard_deviation
and I am trying to create the dictionary in that way. How can I create such a dictionary so that I can print a word such as ‘hunger’ from the function and get its score and std deviation?
Note that if your
wordcan have atabcharacter in it, but you’re guaranteed that you only have 3 fields (word, score, std), you can split the string from the right (str.rsplit), only splitting twice (resulting in 3 fields at the end). e.g.word,score,std = line.rsplit(None,2).As mentioned in the comments above, you can also use the
csvmodule to read these sorts of files —csvreally shines if your fields can be “quoted”. e.g.:If you don’t have that scenario, then I find that
str.splitworks just fine.Also, unrelated, but your code calls
make_happiness_tabletwice (the first time you don’t assign the return value to anything). The first call is useless (all it does is read the file and build a dictionary which you can never use). Finally,opening andcloseingtheFileat the beginning of your script is also just a waste since you don’t do anything with the file there.