为什么Python 2认为这些字节是麦克风表情符号,而Python 3却不呢?

Jar*_*red 4 python unicode python-2.x python-3.x emoji

我在数据库中有一些数据,该数据是用户输入的“ BTS ??> BTS”,即“ BTS” +棒球表情+“> BTS” +麦克风表情。当我从数据库中读取它,对其进行解码并在Python 2中进行打印时,它会正确显示表情符号。但是,当我尝试在Python 3中解码相同的字节时,它会以失败UnicodeDecodeError

Python 2中的字节:

>>> data
'BTS\xe2\x9a\xbe\xef\xb8\x8f>BTS\xed\xa0\xbc\xed\xbe\xa4'
Run Code Online (Sandbox Code Playgroud)

将它们解码为UTF-8会输出以下unicode字符串:

>>> 'BTS\xe2\x9a\xbe\xef\xb8\x8f>BTS\xed\xa0\xbc\xed\xbe\xa4'.decode('utf_8')
u'BTS\u26be\ufe0f>BTS\U0001f3a4'
Run Code Online (Sandbox Code Playgroud)

在Mac上打印该unicode字符串会显示棒球和麦克风表情符号:

>>> print u'BTS\u26be\ufe0f>BTS\U0001f3a4'
BTS??>BTS
Run Code Online (Sandbox Code Playgroud)

但是在Python 3中,解码与UTF-8相同的字节会给我一个错误:

>>> b'BTS\xe2\x9a\xbe\xef\xb8\x8f>BTS\xed\xa0\xbc\xed\xbe\xa4'.decode('utf_8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 13: invalid continuation byte
Run Code Online (Sandbox Code Playgroud)

特别是最后6个字节(麦克风表情符号)似乎有点问题:

>>> b'\xed\xa0\xbc\xed\xbe\xa4'.decode('utf_8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte
Run Code Online (Sandbox Code Playgroud)

此外,其他工具(例如此在线十六进制到Unicode转换器)告诉我这些字节不是有效的Unicode字符:

https://onlineutf8tools.com/convert-bytes-to-utf8?input=ed%20a0%20bc%20ed%20be%20a4

为什么Python 2和编码用户输入的任何程序都认为这些字节是麦克风表情符号,而Python 3和其他工具却不这样呢?

jjr*_*sey 5

看起来有几个网页可以帮助回答您的问题:

如果我使用Python 3的“ surrogatepass”错误处理程序解码从Python 2获得的字节,那就是:

b'BTS\xe2\x9a\xbe\xef\xb8\x8f>BTS\xed\xa0\xbc\xed\xbe\xa4'.decode('utf_8',
    errors = 'surrogatepass')
Run Code Online (Sandbox Code Playgroud)

然后我得到了字符串'BTS??>BTS\ud83c\udfa4',这'\ud83c\udfa4'是代表代理emogi的替代对。

您可以返回Python 3中的麦克风,方法是使用“ surrogate pass”将具有代理对的字符串编码为UTF-16并将其解码为UTF-16:

>>> string_as_utf_8 = b'BTS\xe2\x9a\xbe\xef\xb8\x8f>BTS\xed\xa0\xbc\xed\xbe\xa4'.decode('utf_8', errors='surrogatepass')
>>> bytes_as_utf_16 = string_as_utf_8.encode('utf_16', errors='surrogatepass')
>>> string_as_utf_16 = bytes_as_utf_16.decode('utf_16')
>>> print(string_as_utf_16)
BTS??>BTS
Run Code Online (Sandbox Code Playgroud)