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”,则会出现相同的错误。为什么会这样?编辑:问题是在文本中跳过行。解决了的。在
注意,您已经在迭代文件行,块以
for line in infile
开始,因此不需要在其中执行infile.readline()
。在你也可以在发送到你的函数之前检查你的行格式(或者检查函数中的格式,不管你喜欢什么)。在
我打赌这是一个典型的标签对空间的问题。由于IDE格式或搜索和替换的混乱,您的文件实际上可能是空格分隔的。在
试试这个:
如果这不起作用,手动确定每行中每个值之间有多少空格,然后用它替换伪的\u TAB。诚然,这是一个有点粗略的补丁。。。在
有时
infoStr
行可能不包含要拆分的字符(例如,空行''
)。把这个包起来,你应该没事的。在然后在实例化
Student
之前,您需要处理None
情况。在相关问题 更多 >
编程相关推荐