python-3.x - 为什么有些表情符号没有转换回它们的表示形式?
问题描述
我正在研究表情符号检测模块。对于某些表情符号,我观察到奇怪的行为,即在将它们转换为 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 转义字符串时,会呈现两个表情符号,但第三个示例未能转换精确的表情符号,在这种情况下该怎么办?
解决方案
'\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
推荐阅读
- twitter-bootstrap - 如何在 Blazor 应用程序中使用 Bootstrap Collapse
- java - 阿拉伯语文本显示问题
- c++ - 初始化 char* 并为特定数量分配内存会添加 nullptr 字符
- bash - 在 bash 中生成 0.5 到 1.5 之间的随机数
- c++ - 获得焦点后选择所有内容
- c++ - 在 Windows 10 上为 CMake 设置 3rd 方库环境
- caching - Elixir:将定时状态包装在 GenServer 中的最佳实践?
- python - MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'hp'@'localhost' (using password: NO)")
- blockchain - 在 Android 手机上运行的 Tendermint
- java - 如何在 Lagom 中提供静态资产?