为什么有些表情符号不能转换回其表现形式?

问题描述 投票:0回答:1

我正在开发表情符号检测模块。对于一些emojis,我观察到一个奇怪的行为,那就是在将它们转换为utf-8编码后,它们没有被转换回它们的原始表示形式。我需要将它们准确的彩色表示作为API响应发送,而不是发送unicode转义字符串。任何线索?

In [1]: x = "example1: 🤭 and example2: 😁 and example3: 🥺" 

In [2]: x.encode('utf8')                                                                                                                                                                                                          
Out[2]: b'example1: \xf0\x9f\xa4\xad and example2: \xf0\x9f\x98\x81 and example3: \xf0\x9f\xa5\xba'

In [3]: x.encode('utf8').decode('utf8')                                                                                                                                                                                           
Out[3]: 'example1: \U0001f92d and example2: 😁 and example3: \U0001f97a'

In [4]: print( x.encode('utf8').decode('utf8')  )                                                                                                                                                                                 
*example1: 🤭 and example2: 😁 and example3: 🥺*

例子中使用的链接表情符号

更新1:通过这个例子,一定可以解释得更清楚了。在这里,当我发送unicode转义字符串时,有两个emojis被呈现出来,但第三个exampled未能转换为准确的emoji,这种情况下该怎么办?

API View CodeAPI Response using Postman

python-3.x unicode utf-8 python-unicode unicode-escapes
1个回答
3
投票

'\U0001f92d' == '🤭'True. 这是一个转义码,但仍然是同一个字符...两种显示输入方式。 前者是 repr() 的字符串,打印调用 str(). 例子:当Python生成repr()时,如果它认为显示器不能处理这个字符,它就会使用转义码表示。

>>> s = '🤭'
>>> print(repr(s))
'\U0001f92d'
>>> print(str())
🤭
>>> s
'\U0001f92d'
>>> print(s)
🤭

当Python生成repr()时,如果它认为显示器不能处理这个字符,它就会使用转义码表示。 字符串的内容还是一样的...Unicode码点。

这是一个调试功能。 例如,白色的空间是空格还是制表符? 这个 repr() 的字符串,通过使用 \t 作为转义码。

>>> s = 'a\tb'
>>> print(s)
a       b
>>> s
'a\tb'

至于为什么一个转义码用于一个表情符号而不是另一个,这取决于所使用的 Python 版本所支持的 Unicode 版本。

Pyton 3.8 使用 Unicode 9.0,而你的一个表情符号并没有定义在那个版本级别上。

>>> import unicodedata as ud
>>> ud.unidata_version
'9.0.0'
>>> ud.name('😁')
'GRINNING FACE WITH SMILING EYES'
>>> ud.name('🤭')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: no such name
© www.soinside.com 2019 - 2024. All rights reserved.