2017-03-23 29 views
2

我已經嘗試了兩種方法來解決這個問題,但會導致另一個錯誤。首先試圖通過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錯誤...

+0

了一個請張貼問題的工作示例。這很可能是您打開文件進行寫入的問題。 – tdelaney

+0

你使用2.7的任何原因? Python 3中的Unicode支持要好得多。只有當你有一些遺留依賴時,2.x纔有用。 – tdelaney

回答

1

嘗試解析您的字典有寫入csv之前的unicode值。

def convert(input): 
    if isinstance(input, dict): 
     return {convert(key): convert(value) for key, value in input.iteritems()} 
    elif isinstance(input, list): 
     return [convert(element) for element in input] 
    elif isinstance(input, unicode): 
     return input.encode('utf-8') 
    else: 
     return input 

if __name__ == "__main__": 
    utf_route = convert(route) 

所以,如果你的錯誤而寫的CSV請嘗試以下

import codecs 

with codecs.open("local/file1.csv", "w", encoding='utf8') as f: 
    writer = csv.writer(f, delimiter=",") 
    writer.writerow(data.keys()) 
    writer.writerow(data.values()) 
+0

我試圖把它放在這個部分,但錯誤依然存在......:對於路由中的路由: if __name__ ==「__main__」: utf_route = convert(route) try: route_color = route [「properties」 ] [「route_color」] route_color = route_color.strip('#') print(route_color) – Reiion

+0

是否有可能使用'import pdb; pdb.set_trace()'來挖掘正確的錯誤位置。我不確定你的輸入現在看起來有多長。 – Varad

+0

讓我試試,如果我可以。對不起,這是我在python中的第一個項目,我真的沒有時間玩弄調試器工具,不像java – Reiion

相關問題