gpt4 book ai didi

python - 来自 urlopen 的乱码

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:06 27 4
gpt4 key购买 nike

我正在尝试从下面代码中的地址读取一些 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:

最佳答案

>>> 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'}

要么设置一个 header 以阻止站点发送 gzip 编码的响应,要么先对其进行解码。

关于python - 来自 urlopen 的乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7964726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com