2016-12-14 79 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')]