簡體   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