我正在閱讀來自許多不同國家的unicode字符的文本文件。該文件中的數據也是JSON格式。UnicodeDecodeError:'ascii'編解碼器無法解碼字節... Python 2.7和
我正在使用CentOS機器。當我在終端中打開文件時,unicode字符顯示得很好(所以我的終端配置爲unicode)。
當我在Eclipse中測試我的代碼時,它工作正常。當我跑我的在終端的代碼,它拋出一個錯誤: 的UnicodeDecodeError:「ASCII」編解碼器不能在17位解碼字節0xc3:有序不在範圍內(128)
for line in open("data-01083"):
try:
tmp = line
if tmp == "":
break
theData = json.loads(tmp[41:])
for loc in theData["locList"]:
outLine = tmp[:40]
outLine = outLine + delim + theData["names"][0]["name"]
outLine = outLine + delim + str(theData.get("Flagvalue"))
outLine = outLine + delim + str(loc.get("myType"))
flatAdd = ""
srcAddr = loc.get("Address")
if srcAddr != None:
flatAdd = delim + str(srcAddr.get("houseNumber"))
flatAdd = flatAdd + delim + str(srcAddr.get("streetName"))
flatAdd = flatAdd + delim + str(srcAddr.get("postalCode"))
flatAdd = flatAdd + delim + str(srcAddr.get("CountryCode"))
else:
flatAdd = delim + "None" + delim + "None" + delim +"None" + delim +"None" + delim +"None"
outLine = outLine + FlatAdd
sys.stdout.write(("%s\n" % (outLine)).encode('utf-8'))
except:
sys.stdout.write("Error Processing record\n")
所以一切工作,直到它到達StreetName,它在UnicodeDecodeError中崩潰,這是非ASCII字符開始顯示的位置。
我可以通過添加.encode修復實例( 'UTF-8'):
flatAdd = flatAdd + delim + str(srcAddr.get("streetName").encode('utf-8'))
但然後將其與UnicodeDecodeError錯誤下一行崩潰:
outLine = outLine + FlatAdd
我已經在這一類問題上徘徊了一個月。任何反饋將不勝感激!
[如何阻止疼痛?](http://nedbatchelder.com/text/unipain.html) – 2013-03-26 20:25:08
Robᵩ,謝謝!看到字節後我感覺像Neo。 – user1826936 2013-03-28 14:29:44