【问题标题】:Take the average for scores in a given file for Python取给定文件中 Python 分数的平均值
【发布时间】:2012-10-18 16:53:01
【问题描述】:

我正在制作一个函数,它作为输入(字符串,字典)并返回一个浮点数。该函数接受来自要评估的文件中的文本和单个单词的字典作为输入。该函数必须返回整个文本的分数。也就是说,分数是出现的单词分数的平均值。

我有一个 .csv 文件,其中包含一个单词列表,每个单词都有一个分数和标准偏差。在文件中,每一行的格式为

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)

【问题讨论】:

  • 不要使用数据类型作为变量名(例如:dict)。这很混乱。
  • 另外,如果将始终评估为 false,因为您正在将字符串中的每个单词的每个单词的 dict 重置为一个空值,并且可能发布您当前的代码。如果您发布示例,请准确识别它们(例如:line.split()、dict = dict() 等)
  • 连这个都跑不了!

标签: python string dictionary average


【解决方案1】:

我不确定您要执行的确切数学运算。 我不确定您是否能够读取该文件。

但希望这将提供一些指导。

# 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)

【讨论】:

  • 你不需要 readlines()。你可以只做'for line in csv'。您也可以只使用 defaultdict 来避免在加载之前检查字典中是否存在该单词。
  • @juniper- 是的。但是readlines 如果我没记错的话已经为你做了.strip()。否则你将不得不以一种丑陋的方式照顾.strip()。据我所知,列表列表没有默认字典。
  • 根据文档 readlines() 不会为您执行 strip() 。默认字典可以像这样'a = defaultdict(lambda:[0,0])'。
  • 你用的是什么python?我有 2.6 :(
【解决方案2】:

根据我阅读您的解释的理解,这可能是您需要的。

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)

【讨论】:

  • 我完全不明白你的幸福指数。它并没有真正做任何事情。你只是在数所有的分数。与那里的每个单词的分数无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 2016-08-01
相关资源
最近更新 更多