从文本文件导入数据时如何增加 Python 词典中的值?
How to increment values in a Python Dictionary when importing data from a text file?
我在名为 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')
我希望能够增加字典中的值。例如,他们 key/value 对 David 是:
David : 1030.1
(文件中 3 个值的总和)
我收到以下错误:
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
有人知道如何解决这个问题吗?
谢谢!
您正在解析一个值为 str
的文本文件,但是您将 defaultdict
初始化为 float
,因此它需要浮点数。
d[key.strip()] += val.strip()
上面应该改为:
d[key.strip()] += float(val.strip())
我将留给您解决如何处理转换失败的问题。
由于程序试图将整数添加到字符串而导致的错误,
即David:negative,所以可以用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']
我在名为 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')
我希望能够增加字典中的值。例如,他们 key/value 对 David 是:
David : 1030.1
(文件中 3 个值的总和)
我收到以下错误:
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
有人知道如何解决这个问题吗?
谢谢!
您正在解析一个值为 str
的文本文件,但是您将 defaultdict
初始化为 float
,因此它需要浮点数。
d[key.strip()] += val.strip()
上面应该改为:
d[key.strip()] += float(val.strip())
我将留给您解决如何处理转换失败的问题。
由于程序试图将整数添加到字符串而导致的错误,
即David:negative,所以可以用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']