考虑到我文件的内容:
"ID","Name","Type 1","Type 2","Generation","Legendary"
1,"Bulbasaur","Grass","Poison",1,"FALSE"
6,"Charizard","Fire","Flying",1,"FALSE"
4,"Charmander","Fire","",1,"FALSE"
169,"Crobat","Poison","Flying",2,"FALSE"
146,"Moltres","Fire","Flying",1,"TRUE"
643,"Reshiram","Dragon","Fire",5,"TRUE"
641,"Tornadus, (Incarnate Form)","Flying","",5,"TRUE"我使用readline()来创建每个字符串的列表,作为它自己的行。
然后,我尝试将这些字符串格式化为以下格式:
'Bulbasaur': (1, 'Grass', 'Poison', 1, False)我需要确保准确的报价是正确的,所有的小写和大写都是正确的。我还必须确保将类型设置为所需的类型。
当我迭代或格式化字符串(剥离和拆分)时,我收到了一些错误:
TypeError: 'int' object is not iterable
AttributeError: 'int' object has no attribute 'split'我对这需要如何运作感到非常困惑。我的整体功能运行,但没有返回正确的结果。示例:它在字典中返回charmander的信息,而不是bulbasaur。
这是我的功能,它真的到处都是:
def read_info_file(filename): #accept file
file= open(filename)
lines=file.readlines()[1:] #skip first header line
d={}
for line in lines:
split_line=line.split(',') #get individual strings
legendary=True
if 'F' == split_line[-1].strip('"')[0]: #check last position if t or f to format legendary correctly
legendary=False
if len(split_line) > 6:
(k,v)=(split_line[1]+split_line[2].strip('"'), #puts right order and removes excess quotations
(int(split_line[0]),split_line[3].strip('"'),split_line[4].strip('"'),
int(split_line[5]),legendary))
else:
(k,v)=(split_line[1].strip('"'),
(int(split_line[0]),split_line[2].strip('"'),split_line[3].strip('"'),
int(split_line[4]),legendary))
d.update([(k,v)])
file.close()
return d发布于 2017-04-25 21:27:59
使用内置的csv模块可以简化事情:
import csv
from pprint import pprint
def read_info_file(filename):
with open(filename,'r',newline='') as f:
r = csv.reader(f)
next(r) # skip header
d = {}
for id,name,type1,type2,generation,legendary in r:
d[name] = int(id),type1,type2,int(generation),legendary=='TRUE'
return d
pprint(read_info_file('input.txt'))输出
{“牛头龙”:(1,“草”,“毒药”,1,假),“沙蜥蜴”:(6,“火”,“飞”,1,假),“查曼德”:(4,“火”,“1”,“假”),“克罗巴特”:(169,“毒药”,“飞”,2,“假”),“摩尔茨”:(146,“火”,“飞”,1,真),“雷希拉姆”:(643,‘龙’,‘火’,5,真),'Tornadus,(Incarnate形式)‘:(641,’飞‘,'',5,真)}
https://stackoverflow.com/questions/43618618
复制相似问题