twitter趋势api UnicodeCodeError:&x27;utf8';编解码器可以';t解码位置1中的字节0x8b:意外代码字节

twitter趋势api UnicodeCodeError:&x27;utf8';编解码器可以';t解码位置1中的字节0x8b:意外代码字节,twitter,Twitter,我试图遵循《挖掘社交网络》一书的示例代码,1-3 我知道它是旧的,所以我遵循网页上的新示例 但是,有时,我在实现代码时会遇到错误信息: [ trend.decode('utf-8') for trend in world_trends()[0]['trends'] ] 错误信息如下所示: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.mac

我试图遵循《挖掘社交网络》一书的示例代码,1-3

我知道它是旧的,所以我遵循网页上的新示例

但是,有时,我在实现代码时会遇到错误信息:

[ trend.decode('utf-8') for trend in world_trends()[0]['trends'] ]
错误信息如下所示:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/twitter/api.py", line 167, in __call__
File "build/bdist.macosx-10.6-universal/egg/twitter/api.py", line 173, in _handle_response
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“build/bdist.macosx-10.6-universal/egg/twitter/api.py”,第167行,在调用中__
文件“build/bdist.macosx-10.6-universal/egg/twitter/api.py”,第173行,在响应中
文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/utf_8.py”,第16行,解码
返回编解码器.utf_8_解码(输入,错误,真)
UnicodeDecodeError:“utf8”编解码器无法解码位置1:意外代码字节中的字节0x8b
这种情况并不总是发生,但我认为没有一个程序员喜欢这种“随机”的情况

有人能在这个问题上帮我吗?问题是什么?我如何解决这个问题

非常感谢~

默认情况下,如果遇到不知道如何解码的字节,decode()将抛出错误

您可以使用
trend.decode('utf-8','replace')
trend.decode('utf-8','ignore')
不抛出错误并自动忽略它


位置1的字节0x8b通常表示数据流已压缩。有关类似问题,请参阅和

要解压缩数据流,请执行以下操作:

buf = StringIO.StringIO(<response object>.content)
gzip_f = gzip.GzipFile(fileobj=buf)
content = gzip_f.read()
buf=StringIO.StringIO(.content)
gzip_f=gzip.gzip文件(fileobj=buf)
content=gzip_f.read()

我在使用python请求的库中看到了这一点。
0x8b
来自gzip头:
1F 8B 08
。这是gzip压缩数据。更新:这是由于。感谢您指出这一点。帮助我发现我无意中压缩了一些不应该被压缩的文件。