【问题标题】:How to increment values in a Python Dictionary when importing data from a text file?从文本文件导入数据时如何在 Python 字典中增加值?
【发布时间】:2021-01-01 13:57:26
【问题描述】:

我在一个名为 my_text.txt 的文件中有以下文本:

David: 2
Barbara: 97.2
David: negative
William:

Lynn: 725
Nancy   : 87
     David:       54
Lewis: 18.30
Sue:   3193.74
James: 41.73

David: 974.1

注意空白行和非数字值。这是我从文件中导入数据并创建字典的代码:

import collections
def make_dictionary(file_name):
    d = collections.defaultdict(float)
    with open(file_name, 'r') as file:
        for line in file:
            line = line.strip()
            
            # skip blank lines
            if line == '':
                continue
            
            # split on the colons
            elif ':' in line:
                key, val = line.split(':')
                
                d[key.strip()] += val.strip()
        
    return d

make_dictionary('my_text.txt')

我希望能够增加字典中的值。例如,David 的键/值对将是:

David : 1030.1

(文件中3个值的总和)

我收到以下错误:

TypeError: unsupported operand type(s) for +=: 'float' and 'str'

有没有人知道如何解决这个问题?

谢谢!

【问题讨论】:

  • 您可以检查条目是否为 'negative' ,然后将其更改为 0
  • 当然可以,但是您需要决定如何处理它。跳过值?回退到某个默认值?中止并通知用户?

标签: python io


【解决方案1】:

由于程序试图将整数添加到字符串而导致的错误,

即David:否定的,所以你可以使用 try except 来处理。

r = []
with open('t.txt', 'r') as file:
    for line in file:
        line = line.strip()
        # skip blank lines
        if line == '':
            continue
        # split on the colons
        elif ':' in line:
            key, val = line.split(':')
            # try converting it into float else set it set as 0. 
            try:
                val = float(val.strip())
            except:
                val = 0
            r.append({'name': key.strip(), 'val': val})

那么你可以这样总结:

d = collections.defaultdict(float)
for item in r:
    d[item['name']] += item['val']

【讨论】:

  • 完美运行并处理所有类型问题。谢谢!
【解决方案2】:

您正在解析一个文本文件,其值为str,但是您将defaultdict 初始化为float,因此它需要浮点数。

d[key.strip()] += val.strip()

以上应改为:

d[key.strip()] += float(val.strip())

我将由您来决定如何处理转换失败。

【讨论】:

  • 我要问的问题是如何处理转换失败...
  • 您的代码没有显示任何转换,您只需将其保留为字符串
  • 我可以检查一下是否valisnumeric == False,如果是,则将零写入val 并继续?
  • 肯定是一种选择,你为什么不试试看它是否有效
猜你喜欢
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多