首页 > 解决方案 > 为什么有些表情符号没有转换回它们的表示形式?

问题描述

我正在研究表情符号检测模块。对于某些表情符号,我观察到奇怪的行为,即在将它们转换为 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 转义字符串时,会呈现两个表情符号,但第三个示例未能转换精确的表情符号,在这种情况下该怎么办?

API 查看代码 使用 Postman 的 API 响应

标签: python-3.xunicodeutf-8python-unicodeunicode-escapes

解决方案


'\U0001f92d' == ''True。它是一个转义码,但仍然是同一个字符......两种显示/输入方式。前者是repr()字符串的,打印调用str()。例子:

>>> 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

推荐阅读