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,所以代碼會跳出本次循環,執行下一次循環。
這樣處理后,程序執行時不再異常。
(也許有更好異常的處理方式)