在Python中拆分文件中的数据

2024-09-26 18:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

class Student:

    def __init__(self, name, hours, qpoints):
        self.name = name
        self.hours = float(hours)
        self.qpoints = float(qpoints)

    def getName(self):
        return self.name

    def getHours(self):
        return self.hours

    def getQPoints(self):
        return self.qpoints

    def gpa(self):
        return self.qpoints/self.hours

def makeStudent(infoStr):

    name, hours, qpoints = infoStr.split("\t")


    return Student(name, hours, qpoints)

def main():
    fileName = input("Enter file name: ")
    infile = open(fileName, "r")

    best = makeStudent(infile.readline())

    for line in infile:
        s = makeStudent(line)
        if s.gpa() > best.gpa():
            best = s

    infile.close()

    print("The best student is:", best.getName())
    print("hours:", best.getHours())
    print("GPA:", best.gpa())

if __name__ == '__main__':
    main()

我想从一个文本文件中读取一行,用“\t”或“,”将其拆分,这样我就可以将它分配给变量,然后得到“ValueError:没有足够的值来解包makeStudent(infoStr)函数中的解包(预期为3,得到1)”。我使用的文件是正确写入的,如果我编辑文件并将其编码为“,”而不是“\t”,则会出现相同的错误。为什么会这样?编辑:问题是在文本中跳过行。解决了的。在


Tags: nameselfreturnmaindeffloatstudentinfile
3条回答

注意,您已经在迭代文件行,块以for line in infile开始,因此不需要在其中执行infile.readline()。在

你也可以在发送到你的函数之前检查你的行格式(或者检查函数中的格式,不管你喜欢什么)。在

{truncated code}

# This loop will put on each iteration the next line of the file in the "line" var.
for line in infile:

    # You need two commas in your line to be able to split it in 3 values.
    if line.count(",") != 2:
        print("WARN: Invalid format in line: "+line)
        # Of course that you could implement some counter to identify
        # the problematic line location within the file...
        quit()

    s = makeStudent(line)
    if s.gpa() > best.gpa():
        best = s

{truncated code}

我打赌这是一个典型的标签对空间的问题。由于IDE格式或搜索和替换的混乱,您的文件实际上可能是空格分隔的。在

试试这个:

def makeStudent(infoStr):
    FAKE_TAB = '    '
    name, hours, qpoints = infoStr.split(FAKE_TAB)

    return Student(name, hours, qpoints)

如果这不起作用,手动确定每行中每个值之间有多少空格,然后用它替换伪的\u TAB。诚然,这是一个有点粗略的补丁。。。在

有时infoStr行可能不包含要拆分的字符(例如,空行'')。把这个包起来,你应该没事的。在

try:
    name, hours, qpoints = infoStr.split('\t')
except ValueError:
    name, hours, qpoints = None, None, None

然后在实例化Student之前,您需要处理None情况。在

相关问题 更多 >

    热门问题