繁体   English   中英

在类错误之外拆包值

[英]unpacking values outside a class error

我正在尝试读取一个csv文件数据,并使用一个类存储数据。 我的变量不是直接在文件中定义的,而是作为csv文件的输入。 我想读取Line Ground作为Building_Storey类的输入,并使用类方法from_st分割线,但是我收到此错误的too many values to unpack (expected 4)并且如果我分割,错误消息missing 3 required positional arguments线路Ground早些时候code.it看来,他读整行作为一个字符串,并给出了第一个参数整条生产线。 我不知道这段代码有什么问题。

输入csv文件:

TABLE;BuildingStorey;
GbxmlID;Name;Level;Internal Height;
F0;GroundFloor;0;3.7
F1;FirstFloor;4;3.7
F2;SecondFloor;16;8

编码 :

with open('file.csv', 'r')as fp:
    copy = fp.readlines()
    print(copy)
    l = 0
    for line in copy:
        l = l + 1
        if l == 3:
            if 'GroundFloor' in line:
                Ground = line
                print(Ground) 

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):

        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

    @classmethod
    def from_st(cls, Story_st):
        GbxmlID, Name, Level, Internal_Height = Story_st.split(';')
        return cls(GbxmlID, Name, Level, Internal_Height)

Groundfloor = Building_Storey.from_st(Ground)  
print(Groundfloor.GbxmlID)
print(Groundfloor.Name)
print(Groundfloor.Level)
print(Groundfloor.Internal_Height)

输出应为:

  F0;GroundFloor;0;3.7;;;;;;;  # the line I want to read
  GroundFloor.GbxmlID = F0
  GroundFloor.Name = GroundFloor
  GroundFloor.Level = 0
  GroundFloor.Internal_Height = 3.7

您可以跳过前两行“标题”行,然后使用Python的csv库读取每一行,以自动将文本分成每行的值列表。 如果列表包含4个条目,则使用*将值直接传递给您的类,以将每个列表元素作为参数传递给您的类:

import csv

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):
        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

with open('file.csv', newline='') as f_file:    
    csv_file = csv.reader(f_file, delimiter=';')
    header_1 = next(csv_file)
    header_2 = next(csv_file)

    for row in csv_file:
        if len(row) == 4:
            floor = Building_Storey(*row)
            print("ID: {}, Name: {}, Level: {}, Height: {}".format(floor.GbxmlID, floor.Name, floor.Level, floor.Internal_Height))

这将显示:

ID: F0, Name: GroundFloor, Level: 0, Height: 3.7
ID: F1, Name: FirstFloor, Level: 4, Height: 3.7
ID: F2, Name: SecondFloor, Level: 16, Height: 8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM