2016-12-14 78 views
-1

我是新來的蟒蛇,拿起這本書「的Python數據分析」 pydata書問題與Python JSON解碼

反正我試過18頁的書中的第一個代碼,我不斷收到錯誤。試圖再次下載整個文件,但仍然有相同的錯誤。

這是錯誤消息

UnicodeDecodeError Traceback (most recent call last) 
in() 
----> 1 records=[json.loads(line) for line in open(path)] 

in (.0) 
----> 1 records=[json.loads(line) for line in open(path)] 

/Users/gambit_remy08/anaconda/lib/python3.5/encodings/ascii.py in decode(self, input, final) 
24 class IncrementalDecoder(codecs.IncrementalDecoder): 
25 def decode(self, input, final=False): 
---> 26 return codecs.ascii_decode(input, self.errors)[0] 
27 
28 class StreamWriter(Codec,codecs.StreamWriter): 

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 6987: ordinal not in range(128) 

這裏是鏈接到Github的上述螺紋 https://github.com/wesm/pydata-book/issues/48#issuecomment-266333303

+2

你使用什麼Python版本?看起來像Unicode問題。另外,請發佈您的json數據。 – Nevertheless

+0

該文件的最後一行是空行。刪除最後一行,你的代碼將完美工作。 – MYGz

+0

'records = [json.loads(line)for line in open(path,encoding ='utf8')]' –

回答

0

的UnicodeDecodeError錯誤解碼從特定編碼的STR字符串時通常發生。由於編碼僅將有限數量的str字符串映射爲unicode字符,因此非法的str字符序列將導致編碼特定的decode()失敗。

參考here

爲了解決這個問題,你可以使用your_string.decode('utf8', 'ignore')

records=[json.loads(line.decode('utf8', 'ignore')) for line in open(path)] 
0

我已經爲它找到一個解決方案。基本上只需要使用這個,目前工作良好

records = [json.loads(line) for line in open(path, encoding='utf8')]