5

所以我有一个名为 Person 的类,它基本上具有构造函数名称、id、年龄、位置、目的地,我想做的是当我想创建一个新人时,我希望它从一个 txt 文件中打开。

例如,这是我的 Person 类(在 Module,People 中)

class Person :
    def __init__(self, name, ID, age, location, destination):
        self.name = name
        self.ID = ID
        self.age = age
        self.location = location
        self.destination = destination

    def introduce_myself(self):
        print("Hi, my name is " + self.name + " , my ID number is " + str(self.ID) + " I am " + str(self.age) + " years old")

import People

Fred = People.Person("Fred", 12323, 13, "New York", "Ithaca")

Fred.introduce_myself()

所以基本上,我不必手动输入初始化程序“fred,12232”等。我希望它从一个已经写入所有内容的 txt 文件中读取。

这是txt文件中的内容

[Name, ID, Age, Location, Destination]
[Rohan, 111111, 28, Ithaca, New Caanan]
[Oat, 111112, 20, Ithaca, New York City]
[Darius, 111113, 12, Los Angeles, Ithaca]
[Nick, 111114, 26, New Caanan, Ithaca]
[Andrew, 111115, 46, Los Angeles, Ithaca]
[James, 111116, 34, New Caanan, Ithaca]
[Jennifer, 111117, 56, Los Angeles, New Caanan]
[Angela, 111118, 22, New York City, Los Angeles]
[Arista, 111119, 66, New Caanan, Los Angeles]
4

7 回答 7

2

我会使用 JSON 文件,如下所示:

cat people.json
[
 ["Rohan", 111111, 28, "Ithaca", "New Caanan"],
 ["Oat", 111112, 20, "Ithaca", "New York City"]
]

编码:

import json
with open('people.json') as people_file:
  for record in json.load(people_file):
    person = Person(*record) # items match constructor args
    person.introduce_myself()
于 2013-07-10T21:56:34.690 回答
1
instances = {}         #use a dictionary to store the instances

#open the file using `with` statement, it'll automatically close the
#file for you
with open('abc') as f:
    next(f)                 #skip header
    for line in f:          #now iterate over the file line by line        
        data = line.strip('[]').split(', ')  #strip [] first and then split at ', '
        #for first line it'll return:
            #['Rohan', '111111', '28', 'Ithaca', 'New Caanan']  , a list object

        #Now we can use the first item of this list as the key 
        #and store the instance in the instances dict 
        #Note that if the names are not always unique then it's better to use ID as the
        #key for the dict, i.e instances[data[1]] = Person(*data)
        instances[data[0]] = Person(*data)  # *data  unpacks the data list into Person

#Example: call Rohan's introduce_myself
instances['Rohan'].introduce_myself() 

输出:

Hi, my name is Rohan , my ID number is 111111 I am 28 years old
于 2013-07-10T21:55:56.247 回答
1

有几种方法可以做到这一点,最简单的方法是使用标准文件格式,例如csv或序列化,例如JSON 。我发现有标准模块可以做到这一点。

一个例子csv

import csv
with open('persons.csv', newline='') as f:
    dialect = csv.Sniffer().sniff(f.read(1024))
    f.seek(0)
    reader = csv.reader(f, dialect)
    for row in reader:
        This_Person = People.Person(*row)
        This.introduce_myself()

您的文件存在persons.csv并包含

Rohan, 111111, 28, Ithaca, New Caanan
Oat, 111112, 20, Ithaca, New York City
Darius, 111113, 12, Los Angeles, Ithaca
Nick, 111114, 26, New Caanan, Ithaca
Andrew, 111115, 46, Los Angeles, Ithaca
James, 111116, 34, New Caanan, Ithaca
Jennifer, 111117, 56, Los Angeles, New Caanan
Angela, 111118, 22, New York City, Los Angeles
Arista, 111119, 66, New Caanan, Los Angeles
…

如您所见,即使使用强大的模块,它仍然很短,所以请不要为任何非平凡的项目使用拆分线。相信我,我曾经走同样的路,很难从中恢复过来。

于 2013-07-10T21:50:11.867 回答
0

利用 splat 运算符和一些字符串方法。使用您可以将文本文件转换为列表列表,data = [list val for val in file.read().split('\n')]然后调用您的构造函数:

peopleList = []
for person in data:
       people.append(Person(*person))

peopleList 将包含从您的文本文件创建的人员列表

如果您希望人员变量确实按名称定义,您可以使用vars()包含所有局部变量的字典。那么代码将是:

for person in data:
       vars()[str(person[0])]=Person(*person)
于 2013-07-10T21:55:11.393 回答
0

尝试这个:

people = {}
with open('file.txt', 'r') as f:
  data = [ l[1:-2].split(',') for l in f ][1:]
  for row in data:
      people{row[0]} = Person(*row)

people['Rohan'].introduce_myself()
于 2013-07-10T21:58:25.533 回答
0

将您的文本文件导入列表

with open(yourtextfile.txt) as peopleList:
  listOfPeople = peopleList.readlines()

然后,您可以根据 listOfPeople 的长度循环并在每个条目上运行您的函数。

不过,我建议将其设为 json 文件,这样可以更轻松地表达数据。

于 2013-07-10T22:05:44.353 回答
0

您可以将我闪亮的新记录不佳的tsv 模块用于“制表符分隔值”文件,您可以通过以下方式获得:

pip install --user tsv

然后用制表符(而不是空格)分隔所有字段,并在信息注释行前用 # 制作一个文件:

# People file
# Name  ID  Age Location    Destination
Mary    10  45  Hither  Yon
Bob 11  22  Here    There

(从这里复制粘贴不起作用;StackOverflow 用空格替换答案中的制表符。)

然后,使用以下内容阅读它:

import tsv
import People

for parts in tsv.TsvReader(open("people.txt")):
    # This gets run with "parts" holding a list of all the parts on each line.
    # If we don't care about having strings for ID and Age, we can just pass the
    # whle thing as the arguments to Person's __init__ by "dereferencing" the
    # list. See <http://stackoverflow.com/a/2921893/402891>

    People.Person(*parts).introduce_myself()

    # If you do care about type, it's a bit more complicated:
    People.Person(parts[0], int(parts[1]), int(parts[2]), parts[3], 
        parts[4]).introduce_myself() 
    # You might want to define some intermediate variables here for the sake of
    # good style.
于 2013-07-10T22:12:07.590 回答