首页 > 解决方案 > 如何将包含属性的 CSV 文件链接到 Python 类?

问题描述

我有一个类,Person它具有, , 和. 我现在正在尝试添加一个函数,该函数读取一个包含每个人的这些属性的 CSV 文件,以便最终将其打印出来,但我正在努力弄清楚如何将这两者联系起来。nameageweightheight

到目前为止,我已经read_people在底部编写了我的函数,但我不知道从那里去哪里。如何将每行的每个部分链接到nameageweightheight

"""File for creating Person objects"""

class Person:
    """Defines a Person class, suitable for use in a hospital context.
    Data attributes: name of type str
                     age of type int
                     weight (kg) of type float
                     height (metres) of type float
    Methods: bmi()
             status()
    """

    def __init__(self, name, age, weight, height):
        """Creates a new Person object with a specified name, age, weight, and
        height."""

        self.name = name
        self.age = age
        self.weight = weight
        self.height = height


    def bmi(self):
        """Returns the body mass index of the person"""
        return self.weight / (self.height * self.height)

    def status(self):

        if self.bmi() < 18.5:
            return "Underweight"
        if self.bmi() >= 18.5 and self.bmi() < 25:
            return "Normal"
        if self.bmi() >= 25 and self.bmi() < 30:
            return "Overweight"
        if self.bmi() >= 30:
            return "Obese"


    def __str__(self):
        """Returns the formatted string represent of the Person object"""
        name = self.name
        age = self.age
        bmi = self.bmi()
        status = self.status()
        template = "{0} ({1}) has a bmi of {2:3.2f}. Their status is {3}."
        return template.format(name, age, bmi, status)    




def read_people(csv_filename):

    file = open(csv_filename, "r")    
    for line in file:
        line = line.split(",")   



bods = read_people("people1.csv")
for bod in bods:
    print(bod)

csv 文件示例:

Peter Piper,23,89.4,1.82
Polly Perkins,47,148.8,1.67
Griselda Gribble,92,48,1.45
Ivan Ng,19,59,2.0
Lucy Lovelorn,14,50,1.6
Leslie McWhatsit,70,59.2,1.65

标签: pythoncsv

解决方案


尝试这个:

def read_people(csv_filename):
    persons = []  # list for Person objects

    with open(csv_filename, "r") as file:  
        for line in file:
            args = line.split(",")

            for i in range(1, len(args)):  # convert arguments to float
                args[i] = float(args[i])

            persons.append(Person(*args))  # add Person objects to list
    return persons




bods = read_people("people1.csv")
for bod in bods:
    print(bod)
    print()

输出:

Griselda Gribble (92.0) has a bmi of 22.83. Their status is Normal.

Ivan Ng (19.0) has a bmi of 14.75. Their status is Underweight.

Lucy Lovelorn (14.0) has a bmi of 19.53. Their status is Normal.

Leslie McWhatsit (70.0) has a bmi of 21.74. Their status is Normal.

推荐阅读