【发布时间】:2017-09-22 22:29:20
【问题描述】:
鉴于我的文件内容:
"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"
我使用 readlines() 将每个字符串的列表创建为自己的行。
然后我尝试将这些字符串格式化为以下格式:
'Bulbasaur': (1, 'Grass', 'Poison', 1, False)
我需要确保准确的引用是正确的,并且所有的小写和大写都是正确的。我还必须确保将类型制成所需的类型。
当我去迭代或格式化字符串(即剥离和拆分)时,我收到一些错误:
TypeError: 'int' object is not iterable
AttributeError: 'int' object has no attribute 'split'
我对这需要如何工作感到非常困惑。我的整体功能运行但没有返回正确的结果。示例:它在字典中返回charmander 的信息,而不是bulbasaur 的信息。
- 我需要从 readlines() 中获取结果并将每一行作为字符串获取
- 我需要将该字符串格式化为上面提供的格式
- 然后,一旦我有了那个格式,我就需要把它做成字典。
这是我的功能,它真的无处不在:
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
【问题讨论】:
标签: string python-3.x format readlines