在Python中拆分文件中的数据

时间:2018-10-31 20:24:07

标签: python split valueerror

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:没有足够的值要解包(预期3,得到1) )在makeStudent(infoStr)函数中,我使用的文件已正确写入,如果我将文件和代码编辑为“,”而不是“ \ t”,则会收到相同的错误。为什么会这样呢?编辑:问题出在文本的跳过行解决了。​​

3 个答案:

答案 0 :(得分:0)

有时infoStr行可能不包含您要分割的字符(例如,空白行'')。将其包装在try块中,就可以了。

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

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

答案 1 :(得分:-1)

我敢打赌这是一个经典的制表符与空格问题。您的文件实际上可能由于IDE格式而空间分隔,或者搜索并替换了麻烦的文件。

尝试一下:

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

    return Student(name, hours, qpoints)

如果这不起作用,请手动确定每行中每个值之间有多少空格,然后用FAKE_TAB替换。诚然,它的补丁有点粗略...

答案 2 :(得分:-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}