gpt4 book ai didi

python - python 2.7中的base64编码unicode字符串

转载 作者:太空狗 更新时间:2023-10-29 19:32:29 24 4
gpt4 key购买 nike

我使用 requests module 从 Web 服务检索了一个 unicode 字符串, 其中包含二进制文档的字节(碰巧是 PCL)。其中一个字节的值为 248,尝试对其进行 base64 编码会导致以下错误:

In [68]: base64.b64encode(response_dict['content']+'\n')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-68-8c1f1913eb52> in <module>()
----> 1 base64.b64encode(response_dict['content']+'\n')

C:\Python27\Lib\base64.pyc in b64encode(s, altchars)
51 """
52 # Strip off the trailing newline
---> 53 encoded = binascii.b2a_base64(s)[:-1]
54 if altchars is not None:
55 return _translate(encoded, {'+': altchars[0], '/': altchars[1]})

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 272: ordinal not in range(128)

In [69]: response_dict['content'].encode('base64')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-69-7fd349f35f04> in <module>()
----> 1 response_dict['content'].encode('base64')

C:\...\base64_codec.pyc in base64_encode(input, errors)
22 """
23 assert errors == 'strict'
---> 24 output = base64.encodestring(input)
25 return (output, len(input))
26

C:\Python27\Lib\base64.pyc in encodestring(s)
313 for i in range(0, len(s), MAXBINSIZE):
314 chunk = s[i : i + MAXBINSIZE]
--> 315 pieces.append(binascii.b2a_base64(chunk))
316 return "".join(pieces)
317

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 44: ordinal not in range(128)

我觉得这有点令人惊讶,因为 248 在无符号字节的范围内(并且可以保存在字节字符串中),但我真正的问题是:编码此字符串的最佳或正确方法是什么?

我目前的解决方法是:

In [74]: byte_string = ''.join(map(compose(chr, ord), response_dict['content']))

In [75]: byte_string[272]
Out[75]: '\xf8'

这似乎工作正常,生成的 byte_string 能够进行 base64 编码,但似乎应该有更好的方法。有吗?

最佳答案

您有一个要对其进行 base64 编码的 unicode 字符串。问题在于 b64encode() 仅适用于字节,不适用于字符。因此,您需要将 unicode 字符串(它是抽象 Unicode 代码点的序列)转换为字节字符串。

将抽象的 Unicode 字符串映射到具体的字节序列称为编码。 Python 支持多种编码;我建议使用广泛使用的 UTF-8 编码:

byte_string = response_dict['content'].encode('utf-8')

请注意,解码字节的人还需要知道使用哪种编码通过互补的 decode() 函数取回 unicode 字符串:

# Decode
decoded = byte_string.decode('utf-8')

了解有关 Unicode 和编码的更多信息的一个很好的起点是 Python docs , 和 this article乔尔·斯波斯基 (Joel Spolsky) 着。

关于python - python 2.7中的base64编码unicode字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572274/

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