如何将文件中的数据导入类对象?

Posted

技术标签:

【中文标题】如何将文件中的数据导入类对象?【英文标题】:How to import data from file into class object? 【发布时间】:2020-11-16 08:59:26 【问题描述】:

我是 python 新手,正在学习类和对象。

我有一个包含大量 csv 格式的 Pokemon 数据的文件 - 示例如下:

Number,Name,Type1,Type2,HP,Attack,Defense,SpecialAtk,SpecialDef,Speed,Generation,Legendary,Mega
1,Bulbasaur,Grass,Poison,45,49,49,65,65,45,1,FALSE,FALSE
2,Ivysaur,Grass,Poison,60,62,63,80,80,60,1,FALSE,FALSE
3,Venusaur,Grass,Poison,80,82,83,100,100,80,1,FALSE,FALSE
6,Mega Charizard Y,Fire,Flying,78,104,78,159,115,100,1,FALSE,TRUE
10,Caterpie,Bug,,45,30,35,20,20,45,1,FALSE,FALSE
11,Metapod,Bug,,50,20,55,25,25,30,1,FALSE,FALSE
12,Butterfree,Bug,Flying,60,45,50,90,80,70,1,FALSE,FALSE
13,Weedle,Bug,Poison,40,35,30,20,20,50,1,FALSE,FALSE
14,Kakuna,Bug,Poison,45,25,50,25,25,35,1,FALSE,FALSE
20,Raticate,Normal,,55,81,60,50,70,97,1,FALSE,FALSE

我已经定义了我的 Pokemon 类并打开了下面的文件:

pokedex = open('../resource/lib/public/pokedex.csv', 'r')
for line in pokedex:
    row = line.strip().split(",")

class Pokemon:
    def __init__(self, Number, Name, Type1, Type2 = "" , HP, Attack, Defense,
                SpecialAtk, SpecialDef, Speed,Generation, Legendary, Mega):

        self.Number = Number
        self.Name = Name
        self.Type1 = Type1
        self.Type2 = Type2
        self.HP = HP
        self.Attack = Attack
        self.Defense = Defense
        self.SpecialAtk = SpecialAtk
        self.SpecialDef = SpecialDef
        self.Speed = Speed
        self.Generation = Generation
        self.Legendary = Legendary
        self.Mega = Mega

    def total_stats(self):
        total = self.HP+self.Attack+self.Defense+self.SpecialAtk+self.SpecialDef+self.Speed
        return total

我想使用这些数据回答一系列问题,例如:

- What Pokemon has the highest HP statistic?
- Excluding Pokemon that are either Mega or Legendary, what Pokemon has the highest Defense statistic?
- Among Legendary Pokemon, what is the most common type? Include both Type1 and Type2 in your count.
-In terms of the sum of all six stats (HP, Attack, Defense, Special Attack, Special Defense, and Speed), what is the weakest Legendary Pokemon? If there is a tie, list any of the tying Pokemon.

我该怎么做呢?我不知道如何将文件中的数据与口袋妖怪类链接起来。请帮忙!

【问题讨论】:

您的意思是要创建AI来回答问题吗?或者你想做问答游戏? 不,我只是想通过将文件数据读入类对象来回答一些问题。 例如,我可以在打开文件时使用常规循环来回答问题。例如,如果 row[0] == "Bulbasaur",我可以这样做,返回 row[4] 以获取 Bulbasaur 的 HP。但我想用类和对象来做到这一点。 【参考方案1】:

您可以将数据存储在列表中。 This isn't something new。所以,你会做这样的事情

class Pokemon:
    # Read more about the adjustment made by removing the default value in Type2 - https://***.com/a/48370634/5675325
    def __init__(self, Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega):
        self.Number = Number
        self.Name = Name
        self.Type1 = Type1
        self.Type2 = Type2
        self.HP = HP
        self.Attack = Attack
        self.Defense = Defense
        self.SpecialAtk = SpecialAtk
        self.SpecialDef = SpecialDef
        self.Speed = Speed
        self.Generation = Generation
        self.Legendary = Legendary
        self.Mega = Mega

pokemon_list = []

with open('pokemon.csv', newline='') as csv_file:
    #reader = csv.reader(csv_file)
    #next(reader, None)
    results = []
    for line in csv_file:
        words = line.split(',')
        results.append((words[0:]))
    print(results)
    for Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega in results:
        pokemon_list.append(Pokemon(Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega))

pokemon_list.pop(0) # To remove the object created using headers

print(pokemon_list)

# Then do something with the pokemon_list.

在控制台中我们会看到类似这样的内容

如果我们想看看 pokemon_list 变量是什么

单击索引为 3 的列表项中的实例

正如您提到的想要拥有最高 HP 的口袋妖怪,您可以使用 operator.attrgetter() 执行 something like this 以获得该值

from operator import attrgetter

max_HP = max(pokemon_list, key=attrgetter('HP')).HP
max_ind = [obj for obj in pokemon_list if obj.HP == max_HP]

如果我们再调整代码以包含这部分

from operator import attrgetter

class Pokemon:
    # Read more about the adjustment made by removing the default value in Type2 - https://***.com/a/48370634/5675325
    def __init__(self, Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega):
        self.Number = Number
        self.Name = Name
        self.Type1 = Type1
        self.Type2 = Type2
        self.HP = HP
        self.Attack = Attack
        self.Defense = Defense
        self.SpecialAtk = SpecialAtk
        self.SpecialDef = SpecialDef
        self.Speed = Speed
        self.Generation = Generation
        self.Legendary = Legendary
        self.Mega = Mega

pokemon_list = []

with open('pokemon.csv', newline='') as csv_file:
    #reader = csv.reader(csv_file)
    #next(reader, None)
    results = []
    for line in csv_file:
        words = line.split(',')
        results.append((words[0:]))
    #print(results)
    for Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega in results:
        pokemon_list.append(Pokemon(Number, Name, Type1, Type2, HP, Attack, Defense, SpecialAtk, SpecialDef, Speed, Generation, Legendary, Mega))

pokemon_list.pop(0)

#print(pokemon_list)

max_HP = max(pokemon_list, key=attrgetter('HP')).HP
max_ind = [obj for obj in pokemon_list if obj.HP == max_HP]

print(max_ind)

我们将在控制台中得到以下内容

所以我们可以看到列表 max_ind 只有一个值

max_HP 是 80,拥有它的口袋妖怪是 Venusaur。

要排除超级或传奇的口袋妖怪,请从here 中获取灵感,并将其与前面提到的内容结合起来。

【讨论】:

显然我不能在这个问题中使用 csv,必须使用常规文件打开。 @moe92 刚刚基于该更改进行了改进。如果您想知道,我使用的是 Spyder (Python 3.7)。 非常感谢。我终于能够让它工作了。我将文件数据解压缩到 pokemon 实例中,并在拆分字符串后使用循环和列表索引将它们存储在 pokemon_list 中。然后我继续使用列表、字典和循环来回答其余的问题,我把它们都搞定了。整体代码虽然很长而且很乱,但对我的目的来说很好。不太清楚操作符和吸引器,我的 MOOC 中也没有教给我,所以我选择不使用它们。【参考方案2】:

你可以通过创建一个实例来做到这一点

bulbasaur = Pokemon(1,'Bulbasaur','Grass','Poison',45,49,49,65,65,45,1,FALSE,FALSE 2)

【讨论】:

以上是关于如何将文件中的数据导入类对象?的主要内容,如果未能解决你的问题,请参考以下文章

cad如何导入arcgis,详细步骤

我应该如何将对象实例导入核心数据?

如何将一个excel中的数据自动导入到另一个excel

如何将手机中的csv文件的内容导入到SQLite数据库中

如何将 bak 文件导入 SQL Server Express

如何将VFP中的dbf文件导入到sql2000中去,要比较详细的步骤。急!在线等