
58
|
第四章:隱藏在純文字中的壞資料
-"€5, please"-
>>> print(s.decode('iso-8859-1'))
-5, please-
>>> print(len(s.decode('cp1252')))
14
>>> print(len(s.decode('iso-8859-1')))
14
我們現在知道未知編碼的文字能夠成為壞資料。除此之外,更糟糕的是擁有錯誤文字的
編碼,如將 Code Page 1252 與 ISO-8859-1 搞混,也是一種壞資料。
猜測文字編碼
Unix 的
file
工具會決定檔案中的資料是什麼型態。它能夠理解廣泛的檔案型態,包含一
些純文字的字元編碼。在範例 4-2 中的 Python 腳本程式使用不同的編碼產生一些文字資
料。
make_alnum_sample
函式會遞迴的執行前
n
個 Unicode 編碼點來尋找字母與數字的
字元。
codec
參數是用來指定撰寫這些字母與數字字元的編碼方式。
範例
4-2
產生測試資料
>>> def make_alnum_sample(out, codec, n):
"""
Look at the first n unicode code points
if that unicode character is alphanumeric
and can be encoded by codec write the encoded
character to out
"""
for x in xrange(n):
try:
u ...