Python异常集

ValueError: too many values to u

2016-01-13  本文已影响1277人  大猫黄

sketch.txt为两个人的对话内容。文本格式为

角色:台词

以下源码的功能是分解sketch.txt的每一行,将角色和台词根据冒号分解成两部分,形成

角色 said : 台词

的格式重新输出。

data = open("sketch.txt")

for each_line in data:

            role, content = each_line.split(":")

            print "%s said: %s" % (role, content)

data.close()

执行程序时,出现以下异常:

Man said:  You didn't!

Other Man said:  I'm telling you, I did!

Man said:  You did not!

Other Man said:  Oh I'm sorry, is this a five minute argument, or the full halfhour?

Man said:  Ah! (taking out his wallet and paying) Just the five minutes.

Other Man said:  Just the five minutes. Thank you.

Other Man said:  Anyway, I did.

Man said:  You most certainly did not!

Traceback (most recent call last):  File "file.py", line 21, inrole, line_spoken = each_line.split(":")

ValueError: too many values to unpack

从以上输出可以看到,程序在分解到“Man said:  You most certainly did not!”的下一行时出现ValueError异常。

所以自然想到这一行的下一行是什么呢?

打开sketch.txt,可以发现是下面这一行:

Other Man: Now let's get one thing quite clear: I most definitely told you!

仔细观察,这一行有两个冒号,这样的话split(":")会将这一行分解成三部分,但代码中并没有处理这第三部分的代码,所以ValueError提示值过多。

发现了问题那就好解决了,只需为split函数设置一个分割次数的参数就可以了。

role, content = each_line.split(":", 1)

看执行结果:

依然有个ValueError异常,但仔细观察,这已经不是上面那个ValueError,而是一个新的异常

Other Man said:  Oh yes I did!

Man said:  Oh look, this isn't an argument!

Traceback (most recent call last):  File "file.py", line 24, inrole, line_spoken = each_line.split(":", 1)

ValueError: need more than 1 value to unpack

再次打开sketch.txt文档,查看“Man said:  Oh look, this isn't an argument!”的下一行:

(pause)

这一行没有一个冒号,所以split()会出现异常。

发现问题解决问题,跳过这种提示行

修改代码:

data = open("sketch.txt")

for each_line in data:

    if each_line.find(":") < 0:

        print each_line

        continue

    else:

        role, line_spoken = each_line.split(":", 1)

        print "%s said: %s" % (role,line_spoken)

data.close()

find()函数找不到冒号,返回-1,所以代码会跳出本次循环,执行下一次循环。

这样处理后,程序执行时不再异常。

(也许有更好异常的处理方式)

上一篇 下一篇

猜你喜欢

热点阅读