gpt4 book ai didi

尽管我正在执行 str.decode(),但 Python 会抛出 UnicodeEncodeError。为什么?

转载 作者:太空狗 更新时间:2023-10-30 01:41:43 25 4
gpt4 key购买 nike

考虑这个函数:

def escape(text):
print repr(text)
escaped_chars = []
for c in text:
try:
c = c.decode('ascii')
except UnicodeDecodeError:
c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
escaped_chars.append(c)
return ''.join(escaped_chars)

它应该通过相应的 htmlentitydefs 转义所有非 ascii 字符。不幸的是 python 抛出

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

当变量 text 包含 repr()u'Tam\xe1s Horv\xe1th' 的字符串时。

但是,我不使用 str.encode()。我只使用 str.decode()。我错过了什么吗?

最佳答案

这是一个误导性的错误报告,它来自 python 处理解码/编码过程的方式。您试图对一个已经解码的字符串进行第二次解码,这让 Python 函数感到困惑,而 Python 函数反过来又让您感到困惑! ;-) 据我所知,编码/解码过程是由编解码器模块进行的。在某处存在这种误导性异常消息的起源。

您可以自己检查:要么

u'\x80'.encode('ascii')

u'\x80'.decode('ascii')

会抛出一个UnicodeEncode错误,其中一个

u'\x80'.encode('utf8')

不会,但是

u'\x80'.decode('utf8')

又会了!

我猜你对编码和解码的含义感到困惑。简单来说:

                     decode             encode    
ByteString (ascii) --------> UNICODE ---------> ByteString (utf8)
codec codec

但是为什么decode 方法有一个codec 参数?好吧,底层函数无法猜测 ByteString 是用哪个编解码器编码的,因此作为提示,它采用 codec 作为参数。如果未提供,则假定您的意思是隐式使用 sys.getdefaultencoding()

所以当你使用 c.decode('ascii') 你 a) 有一个(编码的)ByteString(这就是你使用解码的原因)b)你想要一个 unicode-representation-object (这就是你使用 decode 的目的)和 c) 编码 ByteString 的编解码器是 ascii。

另见: https://stackoverflow.com/a/370199/1107807
http://docs.python.org/howto/unicode.html
http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
http://www.stereoplex.com/blog/python-unicode-and-unicodedecodeerror

关于尽管我正在执行 str.decode(),但 Python 会抛出 UnicodeEncodeError。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8590912/

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