首页 > 解决方案 > 从 txt 文件创建字典 - 调试

问题描述

name,score #an example
a,1,
s,2,
d,3,
f,4,
g,5,
h,6,
j,7,
k,8,
l,9,
q,10,

这是我的文件。我想把它做成字典 (a:1,s:2...)

number_of_lines = len(open("scores.txt").readlines(  ))
d = {}
with open("scores.txt") as f:
   for line in range(number_of_lines-1):   #-1 removes the last line which is only \n
     (key, value) = line.split(",")
     d[key] = value
print(d)

我不断收到错误 AttributeError: 'int' object has no attribute 'split' 不知道为什么。

你能调试这个吗?

预先感谢,

标签: pythonfiledictionary

解决方案


range()返回数字,而不是实际的行。由于您将 的输出存储rangelines您将无法执行的操作line.split(),因为line它不是实际的行,而是来自range(). 相反,请执行以下操作:

d = {}
with open("scores.txt") as f:
    for line in f:
        key, value = line.split(",")
        d[key] = value
print(d)

如果您需要所在行的索引(您从未使用过,所以我不知道您是否这样做),您可以使用该enumerate功能。

d = {}
with open("scores.txt") as f:
    for index, line in enumerate(f.readlines()):
        key, value = line.split(",")
        d[key] = value
print(d)

评论中提到,文件长度等存在问题。但这可以在 for 循环中安全地检查:

d = {}
with open("scores.txt") as f:
    for index, line in enumerate(f.readlines()):
        if len(line.strip()) <= 0: continue
        elif index == 0: continue # Skip the header or use the CSV lib
        key, value = line.split(",")
        d[key] = value
print(d)

为了更好地理解这一点,您可以通过以下方式在更独立的基础上使用该range功能(如果您不喜欢阅读文档)进行实验:

for line in range(0, 10):
    print(type(line), line)

希望这可以解决您的问题,但也可以教 range 函数的作用。

最后,考虑使用csv模块:

import csv
with open('scores.txt') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')
    for row in reader:
        print(row['name'], row['score'])

专业人士:处理空行,为您将所有内容排序到字典中,跳过标题(或更准确地说,将它们作为每行字典中的键),最后,为您处理大量 CSV“魔术”(例如特殊分隔符、引号字符等)

您可以使用 csv lib内联创建最终结果,尽管它有点慢,但您最好逐行读取和处理数据,除非它是用于这样的数据库目的:

import csv
with open('scores.txt') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')
    d = {row['name']:row['score'] for row in reader}

推荐阅读