从PYTHON中的.txt文件读取类对象

时间:2018-11-15 13:44:27

标签: python

我是Python的新手,正在尝试学习该语言。在过去的一天里,我一直在努力寻找解决此问题的代码,我知道它可能会相对简单。

我想做的是读取一个文本文件,其中包含以下格式的数据,遍历该数据并为其创建一个类对象。谢谢!

class Profile:

    def __init__(self, given_name='', family_name='', email='', gender='', status=''):
        self.__given_name = given_name
        self.__family_name = family_name
        self.__email = email
        self.__gender = gender
        self.__status = status
        self.__number_friends = 0
        self.__friends_list = []


    def set_given_name(self, name):
        self.__given_name = name

    def get_given_name(self):
        return self.__given_name

    def set_family_name(self, name):
        self.__family_name = name

    def get_family_name(self):
        return self.__family_name

    def set_email(self, email):
        self.__email = email

    def get_email(self):
        return self.__email

    def set_gender(self, gender):
        self.__gender = gender

    def get_gender(self):
        return self.__gender

    def set_status(self, status):
        self.__status = status

    def get_status(self):
        return self.__status

    def set_number_friends(self, no_friends):
        self.__number_friends = no_friends

    def get_number_friends(self):
        return self.__number_friends

    def set_friends_list(self, friends_list):
        self.set_number_friends(len(friends_list))
        self.__friends_list = friends_list

    def get_friends_list(self):
        return self.__friends_list

    def __str__(self):
        string = self.__given_name + ' ' + self.__family_name + ' ' + self.__email + ' ' + self.__gender + '\n'
        string += self.__status + '\n'
        string += str(self.__number_friends) + '\n'
        for friend_email in self.get_friends_list():
            string += friend_email + '\n'
        return string


    def add_friend(self, email):

        if self.is_friend(email) == True:
            return False;

        self.__friends_list.append(email)
        self.__number_friends += 1

        return True

    def remove_friend(self, email):

        if self.is_friend(email) == False:
            return False;

        self.__friends_list.remove(email)
        self.__number_friends -= 1

        return True



    def is_friend(self, email):        
        found = False

        for email_address in self.__friends_list:
            if email == email_address:
                found = True

        return found


    def __eq__(self, email):
        if self.__email == email:
            return True
        elif self.__email != email:
            return False
        return NotImplemented

3 个答案:

答案 0 :(得分:1)

python的最佳实践是使用json,内置数据类型为dict:

例如: text_file.json: {"name":"Fox Mulder","email":"fox@findthetruth.com"} reader.py:

import json
with open("text_file.json",'r') as file:
  a=file.readlines()
dict_0=json.loads(a[0])

那是您的读者班级:

class Profile:
  def reader(self,input_dict,*kwargs):
    for key in input_dict:
      try:
        setattr(self, key, input_dict[key])
      except:
        print("no such attribute,please consider add it at init")
        continue

如果您想阅读,请

profile_instance=Profile()
profile_instance.reader(dict_0)

您现在都设置了

答案 1 :(得分:1)

这可能是您想要做的最简单的方法:

您可以编写这样的程序:

test = Profile()
with open('file.txt', 'r') as f:
    test.set_given_name = f.readlines()[0]
    test.set_family_name = f.readlines()[1]
    test.set_email = f.readlines()[2]
    test.set_gender = f.readlines()[3]
    test.set_status = f.readlines()[4]
    test.set_number_friends = f.readlines()[5]
    test.set_friends_list = f.readlines()[6]

和在file.txt中:

John
Doe
johndoe@gmail.com
Male
single
5
['1', '2']

答案 2 :(得分:0)

我假设“文本文件”是指某种CSV / TSV格式,这将是一个非常普遍的用例。它还意味着CSV文件具有某种标题,该标题定义了与您的类的字段名称相对应的字段名称,因此DictReader类为您提供了适当的抽象级别。

csv模块是Python核心模块的一部分,因此您只需导入它,而无需安装任何内容

以下代码段可能用作框架,以进一步围绕它构建代码

import csv

with open('profiles.csv', newline='') as csvfile:
   reader = csv.DictReader(csvfile)
   for row in reader:
      p = Profile(given_name=row['given_name']
                , family_name=row['family_name']
                , email=row['email']
                , gender=row['gender']
                , status=row['status']
      )

      print(p) # print string representation of the class

尽管如此,如果DictReader不能满足您的需要,您还可以根据自己的意愿解析文本文件的每一行,csv模块文档中有一些示例。