【问题标题】:Python errors when formatting strings that came from a list of strings?格式化来自字符串列表的字符串时出现 Python 错误?
【发布时间】: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


    【解决方案1】:

    使用内置的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'))
    

    输出

    {'Bulbasaur': (1, 'Grass', 'Poison', 1, False),
     'Charizard': (6, 'Fire', 'Flying', 1, False),
     'Charmander': (4, 'Fire', '', 1, False),
     'Crobat': (169, 'Poison', 'Flying', 2, False),
     'Moltres': (146, 'Fire', 'Flying', 1, True),
     'Reshiram': (643, 'Dragon', 'Fire', 5, True),
     'Tornadus, (Incarnate Form)': (641, 'Flying', '', 5, True)}
    

    【讨论】:

    • 我希望我能做到!不幸的是,我不允许使用任何导入的模块。
    • @ocean.1234 你应该写一个解析器吗?因为最后一个数据项在引号中嵌入了逗号,所以简单的line.split(',') 将不起作用。
    • 我不确定解析器是什么?
    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多