【发布时间】: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
-
当然可以,但是您需要决定如何处理它。跳过值?回退到某个默认值?中止并通知用户?