从文本文件转换为类对象

时间:2019-03-03 16:33:32

标签: python python-3.x

我正在努力解决一件事,最后我决定在这里寻求帮助。

正如标题所述,我有一个文本文件,其中包含以下内容:

  

Wulkan 4487.9361错误

     

Merkury 56847.1906是

     

Wenus 107710.46639999999是

     

Ziemia 149597.87是

     

火星227388.7624是

     

Faeton 403914.249错误

     

Jowisz 777908.924是

     

土星1425667.7011是

     

Uran 2870783.1253是

     

Neptun 4496911.9722是

     

Pluton 5906123.9076是

现在我正尝试将其转换为带有3个参数的对象,例如

class Planets:
    def __init__(self, name, dist, real):

到目前为止,我做到了:

with open('planety.txt', 'r') as file:
    x = file.read()


for z in x.split("\n"):
    if z:
        planets = z.split(" ")

如何将在可变行星中获得的每个列表准确地归类为物体?

3 个答案:

答案 0 :(得分:1)

这是一种方式:

class Planets:
    def __init__(self, name, dist, real):
        self.name = name

with open('planety.txt', 'r') as file:
    x = file.read()

planets = []
for z in x.split("\n"):
    if z:
        planet = Planets(*z.split())
        planets.append(planet)

for planet in planets:
    print(planet.name)

{*z.split()收到的列表解压缩为Planets.__init__的三个参数

答案 1 :(得分:0)

您要解决此问题的方法有些棘手,这是我的做法

import csv

_storage = {}

class Planets:
    def __init__(self, name, dist, real):
        self.name = name

with open('doc.txt') as file:
    reader = csv.reader(file, delimiter=' ')
    for row in reader:
        if not len(row) == 0:
            name, dist, real = row
            _storage[name] = Planets(name, dist, real)

现在您可以获得具有行星名称的任何物体

答案 2 :(得分:0)

Python具有type.NamedTuple类。在Python≥3.6中,您可以按以下方式使用typing.NamedTuple类:

module Main( main ) where
import Control.Monad.State

data Employee  = EmployeeSW  Int Int | EmployeeHW Int String deriving ( Show )
data Employee' = EmployeeSW'     Int | EmployeeHW'    String deriving ( Show )

scanTeam :: [Employee] -> State (Int,Int) (Either String [Employee'])
scanTeam [    ] = return (Right [])
scanTeam (p:ps) = do
    newEmployee <- scanEmployee p
    case newEmployee of
        Left errorMsg -> return (Left errorMsg)
        Right e -> do
            newTeam <- scanTeam ps
            case newTeam of
                Right n -> return (Right (e:n))
                Left errorMsg -> return (Left errorMsg)

scanEmployee :: Employee -> State (Int,Int) (Either String Employee')
-- actual code for scanEmployee omitted ...

输出:

from typing import NamedTuple

class Planet(NamedTuple):
    name: str
    dist: float
    real: bool

planets = []
with open('planets.txt', 'r') as file:
    for line in file:
        name, dist, real = line.rstrip().split()
        planets.append(Planet(name=name, dist=float(dist), real=(real == 'True')))

for p in planets:
    print(p)

p = planets[0]
print(p.name, p.dist, p.real)