Python 中的 csv 文件中的 Poblate 对象

Poblate objects from csv file in Python

我有一个 csv 文件 paises.csv 如下所示:

Chile;17000000;0.72;FALSE;0
Hanslandia;2000000;0.2;FALSE;91
Bastiland;4000000;0;TRUE;0

第一列是country名字,下面是它的一些特征,比如它的人口。因此,我创建了一个 country class 并尝试创建国家并使用 csv 文件中的特征填充它:

# -*- coding: utf-8 -*-
##Importing libraries
import csv
##Defining classes
class country:
    def __init__(self,inhabitants,tolerance,underground,infected_perc):
        self.inhabitants = inhabitants
        self.tolerance = tolerance
        self.underground = underground
        self.infected_perc = infected_perc

with open('paises.csv', 'r') as f:
    reader = csv.reader(f, delimiter = ";")
    for row in reader:
        row[0]=country(row[1],row[2],row[3],row[4]) 

代码运行。但是,它甚至没有创建国家。当我尝试查看 row 时,我得到的是:

AttributeError("Can't get attribute 'country' on ",)

我认为您需要一个容器来存储您正在创建的国家/地区。我也会考虑把class:

的名字大写
import csv

class Country:
    def __init__(self,inhabitants,tolerance,underground,infected_perc):
        self.inhabitants = inhabitants
        self.tolerance = tolerance
        self.underground = underground
        self.infected_perc = infected_perc

countries = {}
with open('paises.csv', 'r') as f:
   reader = csv.reader(f, delimiter = ";")
   for row in reader:
       countries[row[0]] = Country(row[1], row[2], row[3], row[4])

您想要的国家/地区存储在字典 countries 中,您可以使用其名称作为关键字来访问它们。例如,要访问智利,您可以使用 countries['Chile'].

更新:

如果您想使用列表而不是字典,您应该在 class 中添加一个字段来存储国家/地区名称:

import csv

class Country:
    def __init__(self,name, inhabitants,tolerance,underground,infected_perc):
        self.name =  name
        self.inhabitants = inhabitants
        self.tolerance = tolerance
        self.underground = underground
        self.infected_perc = infected_perc

countries = []
with open('paises.csv', 'r') as f:
   reader = csv.reader(f, delimiter = ";")
   for row in reader:
       countries.append(Country(row[0], row[1], row[2], row[3], row[4]))

如果使用列表作为容器,您可以用 countries.append(Country(*row))

替换 countries.append(Country(row[0], row[1], row[2], row[3], row[4]))