【问题标题】:How to get UTF-16 (decimal) in Python?如何在 Python 中获取 UTF-16(十进制)?
【发布时间】:2018-09-29 14:09:03
【问题描述】:

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

emoticon = u'\U0001f498'

我想得到这个字符的utf-16十进制组,根据this website5535756472

我尝试做print emoticon.encode("utf16"),但根本没有帮助我,因为它提供了一些其他字符。

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

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

【问题讨论】:

  • 这里基本上有两个独立的问题:如何将十六进制字符串转换为 unicode 字符(或代码点),以及如何将 unicode 字符转换为 utf-16 十进制组。您介意我们删除第一个问题,并假设输入是 unicode 字符或代码点,而不是十六进制字符串吗?
  • 看,与此同时,我在这里stackoverflow.com/questions/49145161/… 找到了这个线程,其中的答案显示了如何做完全相反的事情。但这有点难以理解。如何获得这两个数字?是的,请,任何帮助将不胜感激!提前谢谢你!
  • 只是一个建议:立即升级到 Python 3。一些事情发生了变化,特别是在字符串领域,学习一门过时的语言几乎没有用处。

标签: python python-2.7 unicode encoding utf-16


【解决方案1】:

你可以用utf-16编码encode字符,然后用int.from_bytes(或python 2中的struct.unpack)将编码数据的每2个字节转换为整数。

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

【讨论】:

  • 非常非常非常感谢!
【解决方案2】:

在 Python 2“窄”构建中,它很简单:

>>> emoticon = u'\U0001f498'
>>> map(ord,emoticon)
[55357, 56472]

这适用于 Python 2(窄和宽版本)和 Python 3:

from __future__ import print_function
import struct

emoticon = u'\U0001f498'
print(struct.unpack('<2H',emoticon.encode('utf-16le')))

输出:

(55357, 56472)

这是一个更通用的解决方案,可以为任意长度的字符串打印 UTF-16 代码点:

from __future__ import print_function,division
import struct

def utf16words(s):
    encoded = s.encode('utf-16le')
    num_words = len(encoded) // 2
    return struct.unpack('<{}H'.format(num_words),encoded)

emoticon = u'ABC\U0001f498'
print(utf16words(emoticon))

输出:

(65, 66, 67, 55357, 56472)

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2010-11-16
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多