python - 如何将包含属性的 CSV 文件链接到 Python 类?
问题描述
我有一个类,Person
它具有, , 和. 我现在正在尝试添加一个函数,该函数读取一个包含每个人的这些属性的 CSV 文件,以便最终将其打印出来,但我正在努力弄清楚如何将这两者联系起来。name
age
weight
height
到目前为止,我已经read_people
在底部编写了我的函数,但我不知道从那里去哪里。如何将每行的每个部分链接到name
、age
、weight
和height
?
"""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
解决方案
尝试这个:
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.
推荐阅读
- python-3.5 - ImportError 无法导入名称“dump_options_header”
- ruby - 在 Ruby on rails 中为 1 亿条记录生成 CSV/Excel 文件?
- bash - 从 XML 文档中获取信息并进行比较
- sql - 合并和删除重复条目
- c - 运动问题,跳过字段
- c++ - 用 cudaMemPrefetchAsync 替换 cudaMemcpy2D
- laravel-5 - Lister CRUD 将其他实体列添加到lister
- javascript - 如何在另一个向量上旋转一个向量?
- python - 使用 python 和 tkinter 进行实时 GUI 有一些延迟
- javascript - 将一个变量设置为 JavaScript 函数,其中的内容之前已在页面的另一部分使用 JSON 提要加载