格式化来自字符串列表的字符串时出现Python错误?

时间:2017-04-25 18:44:29

标签: string python-3.x format readlines

鉴于我的文件内容:

"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

1 个答案:

答案 0 :(得分:1)

使用内置的postinstall模块简化了事情:

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'))