python - 如何在 Python 中获取 UTF-16(十进制)?
问题描述
我有一个表情符号的 Unicode 代码点,表示为U+1F498:
emoticon = u'\U0001f498'
我想得到这个字符的 utf-16 十进制组,根据这个网站是55357
和56472
.
我试图这样做print emoticon.encode("utf16")
但根本没有帮助我,因为它提供了一些其他角色。
此外,在将其编码为 UTF-16 之前尝试从 UTF-8 解码print str(int("0001F498", 16)).decode("utf-8").encode("utf16")
也无济于事。
如何正确获取 unicode 字符的 utf-16 十进制组?
解决方案
您可以encode
使用编码的字符utf-16
,然后使用int.from_bytes
(或struct.unpack
在 python 2 中)将编码数据的每 2 个字节转换为整数。
蟒蛇 3
def utf16_decimals(char, chunk_size=2):
# encode the character as big-endian utf-16
encoded_char = char.encode('utf-16-be')
# convert every `chunk_size` bytes to an integer
decimals = []
for i in range(0, len(encoded_char), chunk_size):
chunk = encoded_char[i:i+chunk_size]
decimals.append(int.from_bytes(chunk, 'big'))
return decimals
Python 2 + Python 3
import struct
def utf16_decimals(char):
# encode the character as big-endian utf-16
encoded_char = char.encode('utf-16-be')
# convert every 2 bytes to an integer
decimals = []
for i in range(0, len(encoded_char), 2):
chunk = encoded_char[i:i+2]
decimals.append(struct.unpack('>H', chunk)[0])
return decimals
结果:
>>> utf16_decimals(u'\U0001f498')
[55357, 56472]
推荐阅读
- swift - 在tableview单元格中更改like按钮的颜色
- teradata - 在 teradata 中,您可以将 cte 插入表中吗?
- android - 如何在 android gradle.kts 中定义自定义源集?
- fpga - 如何使用 MyHDL 模块在 PYNQ Z1 上实现以下数学方程?
- django - 如何为我的 django datetimefield 设置默认小时
- php - 三个文件中的多帖子请求 Wordfpress
- android - Flutter Firebase 未正确初始化。您是否将“google-services.json”文件添加到项目中?
- django - 未在 ModelForm 上呈现脆皮表单
- image - 颤振:将CameraImage从相机插件转换为base64而不将图像存储在文件中(直接)
- java - 如何获取以 JSON 格式保存的对象并将其放入控制器中的列表或地图中