2016-11-21 219 views
0

IA具有不斷更新以下數據容器:UnicodeEncodeError:「ASCII」編解碼器不能編碼

data = [] 
     for val, track_id in zip(values,list(track_ids)): 
      #below 
      if val < threshold: 
       #structure data as dictionary 
       pre_data = {"artist": sp.track(track_id)['artists'][0]['name'], "track":sp.track(track_id)['name'], "feature": filter_name, "value": val} 
       data.append(pre_data) 
     #write to file 
     with open('db/json/' + user + '_' + product + '_' + filter_name + '.json', 'w') as f: 
      json.dump(data,f, ensure_ascii=False, indent=4, sort_keys=True) 

,但我越來越喜歡這個有很多的錯誤:

json.dump(data,f, ensure_ascii=False, indent=4, sort_keys=True) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 190, in dump fp.write(chunk) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)

有沒有辦法擺脫這種編碼問題一勞永逸?

有人告訴我,這將做到這一點:

import sys 
reload(sys) 
sys.setdefaultencoding('utf-8') 

但很多人不建議這樣做。

我用python 2.7.10

任何線索?

+0

顯示完整的錯誤跟蹤,所以我們可以看到錯誤來自哪裏。這是Python 2還是3? –

+0

'sys.setdefaultencoding'可能在Python2中工作,但在Python3中不存在。它可以與'print()'一起使用,但不能與寫入文件等其他內容一起使用,因此您必須顯示完整的錯誤消息和產生問題的行。 – furas

+0

@MarkRansom更新,謝謝 –

回答

0

當您寫入以文本模式打開的文件時,Python會爲您編碼該字符串。默認編碼是ascii,它會產生您看到的錯誤;有一個很多字符不能被編碼爲ASCII。

解決方案是以不同的編碼打開文件。在Python 2中,您必須使用codecs模塊,在Python 3中,您可以將encoding=參數直接添加到openutf-8是一個流行的選擇,因爲它可以處理所有的Unicode字符,並且對於JSON來說它是標準的;見https://en.wikipedia.org/wiki/JSON#Data_portability_issues

import codecs 
with codecs.open('db/json/' + user + '_' + product + '_' + filter_name + '.json', 'w', encoding='utf-8') as f: 
+0

您擊敗了我! [RFC](https://tools.ietf.org/html/rfc7159#section-8.1)只允許utf-8,utf-16和utf-32編碼,但對後兩種編碼設置了限制(例如沒有BOM)並暗示utf-8是唯一可以互操作的方法。 'mbcs'會違反rfc。我認爲JSON只是utf-8,並且對其他編碼甚至被允許感到驚訝。 – tdelaney

+0

@tdelaney我從來沒有直接處理過JSON,所以我不知道字符集限制,謝謝!我會編輯答案。 –

0

爲什麼不編碼特定的字符串呢?對引發異常的字符串嘗試使用.encode('utf-8')方法。

1

你的對象有unicode字符串和python 2.x對unicode的支持可能有點多餘。首先,讓我們做演示該問題很短的例子:

>>> obj = {"artist":u"Björk"} 
>>> import json 
>>> with open('deleteme', 'w') as f: 
...  json.dump(obj, f, ensure_ascii=False) 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
    File "/usr/lib/python2.7/json/__init__.py", line 190, in dump 
    fp.write(chunk) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 3: ordinal not in range(128) 

json.dump幫助文本:

啊!有解決方案。使用默認的ensure_ascii=True並獲取ascii轉義的unicode字符或使用codecs模塊以您想要的編碼打開文件。這工作:

>>> import codecs 
>>> with codecs.open('deleteme', 'w', encoding='utf-8') as f: 
...  json.dump(obj, f, ensure_ascii=False) 
... 
>>> 
相關問題