【问题标题】:Creating an object from a txt file and appending it to a list从 txt 文件创建对象并将其附加到列表
【发布时间】:2017-11-07 01:22:37
【问题描述】:

所以我创建了一个包含棒球运动员年份、姓名、统计数据的类。我现在正在尝试从包含玩家信息的 txt 文件中读取并创建对象列表。我似乎不知道该怎么做。

这是课程:

class PlayersYear:
    def __init__(self, year, player, stats):

        self.__year = int(year)
        self.__player = player
        self.__stats = stats

现在我正在尝试从一个列出这样的统计数据的文件中读取,我们将其命名为棒球.txt:

1971Hank Aaron:162:22:3:47:495
2002Barry Bonds:149:31:2:46:403
1974Rod Carew:218:30:5:3:599

我正在尝试在创建 PlayersYear 对象中读取这些内容并将其附加到列表中。我完全迷路了,希望能得到一些帮助。谢谢!

这就是我所拥有的,我知道它错了

def readPlayerFile(filename):
    baseball = []
    file_in = open(filename, 'r')

    lines = file_in.readlines()

    for i in lines:
        baseball.append(PlayersYear(year, name, stats))

    file_in.close()

    return baseball

【问题讨论】:

标签: python


【解决方案1】:

这对你有帮助吗?它只是将玩家姓名、年份和状态分开

def playerList(fileName):
    file = open(fileName, 'r')
    nameList = []
    for line in file:
        line = line[4:]
        name = line.split(":")[0]
        nameList.append(name)
    return nameList


def statusList(fileName,satusLocation):
    file = open(fileName, 'r')
    statusList = []
    for line in file:
        status = line.split(":")[satusLocation]
    statusList.append(status)
    return statusList

def yearList(fileName):
    file = open(fileName, 'r')
    years = []
    for line in file:
        line = line[:4]
        years.append(line)
    return years

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多