Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从txt调用以定义某些内容。。。python_Python - Fatal编程技术网

从txt调用以定义某些内容。。。python

从txt调用以定义某些内容。。。python,python,Python,我有一个名为Person的类,它基本上有构造函数的名称、id、年龄、位置、目的地,我想做的是当我想创建一个新的Person时,我想从一个txt文件中打开它 例如,这是我的Person类(在模块中为People) 基本上,我不用手动输入初始化器“fred,12232”等等。。 我希望它从一个txt文件中读取,该文件包含所有已写入的内容 这就是txt文件将包含的内容 [Name, ID, Age, Location, Destination] [Rohan, 111111, 28, Ithaca,

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

例如,这是我的Person类(在模块中为People)

基本上,我不用手动输入初始化器“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]

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

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
…

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

利用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)
输出:

Hi, my name is Rohan , my ID number is 111111 I am 28 years old

我会使用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()
试试这个:

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()

将文本文件导入列表

with open(yourtextfile.txt) as peopleList:
  listOfPeople = peopleList.readlines()
然后,您可以根据人物列表的长度循环浏览该列表,并对每个条目运行函数


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

您可以使用我的全新文档,用于“制表符分隔值”文件,您可以使用:

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.
导入tsv
引进人才
对于tsv.TsvReader(open(“people.txt”))中的部件:
#运行时,“部件”包含每行上所有部件的列表。
#如果我们不关心ID和年龄的字符串,我们可以通过
#什么是通过“去引用”的方法来对Person的uuu init uuu_uu_u_uu_uu_uu_u_u的论点
#名单。看见
人物。人物(*部分)。自我介绍()
#如果你真的关心类型,那就有点复杂了:
Person.Person(第[0]部分)、int(第[1]部分)、int(第[2]部分)、第[3]部分、,
第[4]部分。自我介绍()
#您可能需要在这里定义一些中间变量,以便
#好的风格。

当然只要使用
文件\u handle.read()
str.split
这个
vars()
把戏很可怕。它为各种恶意代码注入打开了大门。问问小鲍比。你能更详细地解释一下代码吗?我对python有点陌生。@Panthy我已经添加了更多的解释。对不起,再问一点问题。什么是*数据?
*数据
是指将
数据
列表的内容解压缩到
个人
中。
csv
模块也可以处理
tsv
文件。或者sv文件中包含任何分隔符。为什么需要另一个模块?
tsv
支持注释,并且具有更简单的API。另外,我有一个学校作业中的模块,我想我应该把它上传到PyPI。
# People file
# Name  ID  Age Location    Destination
Mary    10  45  Hither  Yon
Bob 11  22  Here    There
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.