gpt4 book ai didi

Python 响应解码

转载 作者:太空宇宙 更新时间:2023-11-03 11:54:33 25 4
gpt4 key购买 nike

对于以下使用 urllib 的行:

# some request object exists
response = urllib.request.urlopen(request)
html = response.read().decode("utf8")

read() 返回什么格式的字符串?我一直在尝试从 Python 的文档中找出这一点,但它根本没有提到它。为什么会有解码decode 是将对象解码 utf-8 还是 utf-8?它从什么格式解码成什么格式? decode 文档也对此只字不提。是 Python 的文档那么糟糕,还是我不理解一些标准约定?

我想将该 HTML 存储在一个 UTF-8 文件中。我会只是进行常规写入,还是需要“编码”回某些内容并写入?

注意:我知道 urllib 已被弃用,但我现在不能切换到 urllib2

最佳答案

问 python :

>>> r=urllib.urlopen("http://google.com")
>>> a=r.read()
>>> type(a)
0: <type 'str'>
>>> help(a.decode)
Help on built-in function decode:

decode(...)
S.decode([encoding[,errors]]) -> object

Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that is
able to handle UnicodeDecodeErrors.

>>> b = a.decode('utf8')
>>> type(b)
1: <type 'unicode'>
>>>

因此,read() 似乎返回了一个 str.decode() UTF-8 解码为 Python 的内部 unicode 格式。

关于Python 响应解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454361/

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