Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 胡言乱语_Python_Utf 8_Urlopen - Fatal编程技术网

Python 胡言乱语

Python 胡言乱语,python,utf-8,urlopen,Python,Utf 8,Urlopen,我正在尝试从下面代码中的地址读取一些utf-8文件。它适用于大多数文件,但对于某些文件,urllib2(和urllib)无法读取 这里显而易见的答案是第二个文件已损坏,但奇怪的是IE读取这两个文件一点问题都没有。该代码已经在XP和Linux上进行了测试,结果相同。有什么建议吗 import urllib2 #This works: f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/145/pg145.txt") line=f.readl

我正在尝试从下面代码中的地址读取一些utf-8文件。它适用于大多数文件,但对于某些文件,urllib2(和urllib)无法读取

这里显而易见的答案是第二个文件已损坏,但奇怪的是IE读取这两个文件一点问题都没有。该代码已经在XP和Linux上进行了测试,结果相同。有什么建议吗

import urllib2
#This works:
f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/145/pg145.txt")
line=f.readline()
print "this works: %s)" %(line)
line=unicode(line,'utf-8') #... works fine

#This doesn't
f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/144/pg144.txt")
line=f.readline()
print "this doesn't: %s)" %(line)
line=unicode(line,'utf-8')#...causes an exception:

您请求的URL似乎引用了一个私有缓存。改为尝试(在中找到)

如果您确实想使用
/cache/
URL:服务器正在向您发送压缩数据,而不是unicode
urllib2
不要求Gzip数据,也不解码它,这是正确的行为。
有关如何解压缩,请参阅。

您知道这不是一个解决方案,但您应该查看库,无论您是否仍要使用urllib,都可以查看请求的源代码,以了解它如何处理utf-8字符串

>>> f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/144/pg144.txt")
>>> f.headers.dict
{'content-length': '304513', ..., 'content-location': 'pg144.txt.utf8.gzip', 'content-encoding': 'gzip', ..., 'content-type': 'text/plain; charset=utf-8'}
设置阻止站点发送gzip编码响应的标头,或者首先对其进行解码