sketch.txt為兩個人的對話內(nèi)容凶伙。文本格式為
角色:臺詞
以下源碼的功能是分解sketch.txt的每一行,將角色和臺詞根據(jù)冒號分解成兩部分苍匆,形成
角色 said : 臺詞
的格式重新輸出刘急。
data = open("sketch.txt")
for each_line in data:
? ? ? ? ? ? role, content = each_line.split(":")
? ? ? ? ? ? print "%s said: %s" % (role, content)
data.close()
執(zhí)行程序時,出現(xiàn)以下異常:
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!”的下一行時出現(xiàn)ValueError異常叔汁。
所以自然想到這一行的下一行是什么呢?
打開sketch.txt检碗,可以發(fā)現(xiàn)是下面這一行:
Other Man: Now let's get one thing quite clear: I most definitely told you!
仔細(xì)觀察据块,這一行有兩個冒號,這樣的話split(":")會將這一行分解成三部分折剃,但代碼中并沒有處理這第三部分的代碼另假,所以ValueError提示值過多。
發(fā)現(xiàn)了問題那就好解決了微驶,只需為split函數(shù)設(shè)置一個分割次數(shù)的參數(shù)就可以了浪谴。
role, content = each_line.split(":", 1)
看執(zhí)行結(jié)果:
依然有個ValueError異常,但仔細(xì)觀察因苹,這已經(jīng)不是上面那個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()會出現(xiàn)異常凶杖。
發(fā)現(xiàn)問題解決問題,跳過這種提示行
修改代碼:
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()函數(shù)找不到冒號款筑,返回-1智蝠,所以代碼會跳出本次循環(huán),執(zhí)行下一次循環(huán)奈梳。
這樣處理后杈湾,程序執(zhí)行時不再異常。
(也許有更好異常的處理方式)