我正在创建一个函数,它接受输入(字符串,字典)并返回一个浮点数。该函数接受来自要评估的文件的文本和单个单词的字典作为输入。该函数必须返回整个文本的分数。也就是说,得分是出现的单词得分的平均值。
我有一个.csv文件,其中包含一个单词列表,每个单词都有一个分数和std偏差。在文件中,每一行采用
形式word{TAB}score{TAB}standard_deviation
我将这些字母全部写成小写并试图取得所有分数的平均值。
到目前为止我有这个但是无法用正确的方法弄清楚平均值:
def happiness_score(string , dict):
sum = 0
for word in string:
dict = dict()
if word in dict:
sum += word
word = string.lower()
word,score,std = line.split()
d[word]=float(score),float(std)
return sum/len(dict)
答案 0 :(得分:0)
我不确定你想要执行的确切数学运算。 并且我不确定你是否能够阅读该文件。
但希望这会提供一些指导。
# to hold your variables
holder_dict = {}
# read the file:
with open("/path/to/file.csv", 'r') as csv_read:
for line in csv_read.readlines():
word, score, std = line.split('\t')
if word in holder_dict.keys():
holder_dict[word][0] += [float(score)]
holder_dict[word][1] += [std]
else:
holder_dict[word] = [[float(score)],[std]]
# get average score
for word in holder_dict.keys():
average_score = sum(holder_dict[word][0])/len(holder_dict[word][0])
print "average score for word: %s is %.3f" % (word, average_score)
答案 1 :(得分:0)
根据我从阅读你的解释中所理解的,这可能就是你所需要的。
def happiness_score(string, score_dict):
total = 0
count = 0
for word in string.lower().split():
if word in score_dict:
total += score_dict[word]
count += 1
return total/count
def compile_score_dict(filename):
score_dict = {}
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
score_dict[row[0].lower()] = int(row[1])
return score_dict
score_dict = compile_score_dict('filename.csv')
happiness_score('String to find score', score_dict)