如果标题含糊不清,我深感抱歉。首先,我想说的是,我已经阅读了所有可以找到的有关python中的Value Error的论坛,我已经实现了它们,但是我的程序仍然无法通过第22行。在底部有更多解释,但是首先我给你“DL”哈哈。
我正在编写一个程序,该程序读取data.txt文件并显示输出。这是项目的目标
Your output should look like: Reading vertices for a polygon with 5 vertices... Vertex 1 has coordinates at (1.70, 4.90) Vertex 2 has coordinates at (6.10, 6.20) Vertex 5 has coordinates at (1.50, 1.40)
Reading vertices for a rectangle having, (of course), 4 vertices... Vertex 1 has coordinates at (7.00, 5.00) ... Your program only needs to echo check the data; there is no requirement during this lab to construct polygon objects, rectangle objects, to do transformations, to undo transformations, or to find and print perimeter.
我的命令行中的错误是:
Reading vertices for polygon with 5 vertices...
Vertex 1 has coordinates at (1.7, 4)
Vertex 2 has coordinates at (.9, 6.1)
Vertex 3 has coordinates at (6.2, 7.0)
Vertex 4 has coordinates at (2.8, 4.8)
Vertex 5 has coordinates at (0.1, 1.)
Reading vertices for polygon with 1 vertices...
Traceback (most recent call last):
File "Read.py", line 22, in <module>
x, y = file.read(8).split( )
ValueError: too many values to unpack (expected 2)
我写的代码是:
file = open("data.txt")
line = file.read(1).strip()
while line != 'Q':
numVertices = file.read(3).strip()
numVertices = int(numVertices)
if numVertices != 4:
print("Reading vertices for polygon with " +
str(numVertices) + " vertices...")
else:
print("Reading vertices for rectangle having " +
str(numVertices) + " vertices...")
for i in range(int(numVertices)):
x, y = file.read(8).split( )
print("Vertex " + str(i + 1) + " has coordinates at (" + x + ", " + y + ")")
line = file.read(1).strip()
file.close()
并且data.txt文件包含:
P 5
1.7 4.9
6.1 6.2
7.0 2.8
4.8 0.1
1.5 1.4
R 4
7.0 5.0
1.0 5.0
1.0 3.0
7.0 3.0
P 4
4.1 5.4
6.9 2.5
2.9 0.8
0.9 2.5
P 3
1.2 4.7
6.5 4.2
4.0 1.7
Q
在第22行中,我尝试添加到.split()中,添加了(“”),(“,”),但没有一个成功。我试图将变量从int更改为float,但是后来我无法连接字符串。所以我很茫然,有人会帮我找出问题所在吗?非常感谢!
最佳答案
您的代码存在问题,它期望使用和指定的格式。观察您的工作:
read(1)
那正好读一个字节。大概期望多边形/退出的类型。然后:
read(3).strip()
为什么是3个字节?好吧,您可能希望字母后面有一个空格,然后是指定顶点数量的数字,必须为1位数字,最后是换行符。总共3个字节。最后,对于每个顶点,
read(8)
8个字节-每个坐标3个(数字,小数点,数字),它们之间有一个空格,最后是新行。
如果有任何字符不正确,它将破坏您的代码。您期望确切的格式。如果您不必使用
read
,则不必-有更简单的方法,特别是逐行阅读。如果必须使用读取,请确保文件格式正确。您提供的示例中至少有 2个空格,有时3个空格 -这会破坏您的代码。最后,始终尝试通过打印调试小型程序-放入for循环中:for i in range(int(numVertices)):
res = file.read(8).split()
print(res)
x,y = res
会完全打印出您正在中断的内容,并给您提示如何进行操作。
关于python - 在Python中,.split()行中存在值错误,返回预期的1。添加空格无济于事。 data.txt有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52208627/