首页 > 解决方案 > 如何在 Python 中获取 UTF-16(十进制)?

问题描述

我有一个表情符号的 Unicode 代码点,表示为U+1F498

emoticon = u'\U0001f498'

我想得到这个字符的 utf-16 十进制组,根据这个网站5535756472.

我试图这样做print emoticon.encode("utf16")但根本没有帮助我,因为它提供了一些其他角色。

此外,在将其编码为 UTF-16 之前尝试从 UTF-8 解码print str(int("0001F498", 16)).decode("utf-8").encode("utf16")也无济于事。

如何正确获取 unicode 字符的 utf-16 十进制组?

标签: pythonpython-2.7unicodeencodingutf-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]

推荐阅读