我已經嘗試了兩種方法來解決這個問題,但會導致另一個錯誤。首先試圖通過encode
和其他試圖strip
(#)假設是被捲入該錯誤的問題:Python:UnicodeEncodeError:'ascii'編解碼器無法對位置78中的字符u' xf1'進行編碼:序號不在範圍內(128)
"color":rcolor,"text_color":tcolor})
File "/usr/lib/python2.7/csv.py", line 152, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 78: ordinal not in range(128)
我的代碼現在看起來像這樣:
routes = db.routes.find()
for route in routes:
try:
color = route["properties"]["color"]
color = color.strip('#')
print(color)
tcolor = route["properties"]["tcolor"]
tcolor = tcolor.strip('#')
print(tcolor)
except KeyError:
color = "0000FF"
tcolor = ""
writer.writerow({"route_id":route["route_id"],
"agency_id":route["properties"]["agency_id"],...,
"route_color":color,"route_text_color":tcolor})
我不太確定爲什麼它總是得到unicode錯誤...
了一個請張貼問題的工作示例。這很可能是您打開文件進行寫入的問題。 – tdelaney
你使用2.7的任何原因? Python 3中的Unicode支持要好得多。只有當你有一些遺留依賴時,2.x纔有用。 – tdelaney