如何附加到新对象?

时间:2013-11-17 15:12:09

标签: python

我在python 3中有这个功能几乎可以像我希望的那样工作:

def read_people_from_file(filename):
    """Function that reads a file and adds them as persons"""
    print("reading file")
    try:
        with open(filename, 'rU') as f:
            contents = f.readlines()
    except IOError:
       print("Error: Can not find file or read data")
       sys.exit(1)

    #Remove blank lines
    new_contents = []
    for line in contents:
        if not line.strip():
            continue
        else:
            new_contents.append(line)

    #Remove instructions from file
    del new_contents[0:3]

    #Create persons (--> Here is my problem/question! <--)
    person = 1*[None]
    person[0] = Person()
    person[0] = Person("Abraham", "m", 34, 1, 140, 0.9, 90, 0.9, 0.9)
    for line in new_contents:
        words = line.split()
        person.append(Person(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8]))
    return person

在最后一段代码中,在“#Create persons”下面,我还没弄明白该怎么做。 如何创建空列表,然后从文件中添加人员? 如果我删除名为“亚伯拉罕”的硬编码人员,我的代码将无效。

该文件是一个文本文件,每行一个人,名称后面有属性。

Person类的一部分如下所示:

class Person:
def __init__(self, name=None, gender=None, age=int(100 or 0), beauty=int(0), intelligence=int(0), humor=int(0), wealth=int(0), sexiness=int(0), education=int(0)):
    self.name = name
    self.gender = gender
    self.age = age
    self.beauty = beauty
    self.intelligence = intelligence
    self.humor = humor
    self.wealth = wealth
    self.sexiness = sexiness
    self.education = education

我希望上面的代码是自我解释的。 我怀疑有更多的蟒蛇方式做我想做的事情。 任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

你可以做到

persons = []
...
for line in new_contents:
    words = line.split()
    persons.append(Person(...))

答案 1 :(得分:1)

总是:

persons = [Person(*line.split()) for line in new_contents]

答案 2 :(得分:0)

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

def readfile():
    data = open("file path to read from","r")            #opens file in read mode
    people = []     
    for line in data:                                    #goes through each line
        people.append(Person(*line.split()))             #creates adds "Person" class to a list. The *line.split() breaks the line into a list of words and passes the elements of the list to the __init__ function of the class as different arguments.
    return people