【问题标题】:Decode emoji into two (or more) code points, using standard libraries使用标准库将表情符号解码为两个(或更多)代码点
【发布时间】:2020-10-12 23:01:38
【问题描述】:

我希望能够将表情符号解码为其对应的代码点,如 here 所示。我仅限于在 2.7 中使用标准库。

例如: ?????? -> U+1F1F2U+1F1E9

我已经设法使用此代码获得了第一个代码点,但我不知道如何提取第二个代码点。一些表情符号有更多的代码点。

to_decode = u'????????'
code = ord(to_decode[0])
if 0xd800 <= code <= 0xdbff:
    code = (code - 0xd800) * 1024 + (ord(to_decode[1]) - 0xdc00) +  + 0x010000

print(hex(code))

【问题讨论】:

    标签: python python-2.7 unicode emoji


    【解决方案1】:

    encodestruct.unpack 的组合可以满足您的需求。

    >>> import struct
    >>> b = to_decode.encode('utf_32_le')
    >>> count = len(b) // 4
    >>> count
    2
    >>> cp = struct.unpack('<%dI' % count, b)
    >>> [hex(x) for x in cp]
    ['0x1f1f2', '0x1f1e9']
    

    【讨论】:

      【解决方案2】:

      对于这个问题,您实际上需要 list() 它将 Unicode 字符分解为其组成代码点

      to_decode = u'??'
      list(to_decode)
      ['?', '?']
      

      作为示例,我创建了孟加拉语字母表的 unicode 可视化

      【讨论】:

      • 请注意,该问题指定了 Python 2.7。 list(to_decode) 将在 Python 2 中返回 [u'\ud83c', u'\uddf2', u'\ud83c', u'\udde9']
      • @Selcuk 甚至不一致,它取决于用于编译特定 Python 版本的标志。
      【解决方案3】:

      这是一种 hack,但您可以使用 unicode 字符串的 repr

      >>> repr(to_decode)
      "u'\\U0001f1f2\\U0001f1e9'"
      

      所以:

      >>> hex(int(repr(to_decode)[4:12], 16))
      '0x1f1f2'
      

      >>> hex(int(repr(to_decode)[14:22], 16))
      '0x1f1e9'
      

      您必须扩展此方法以支持具有两个以上代码点的表情符号。您可以考虑将以上内容与.split("\\U")结合使用。

      【讨论】:

        猜你喜欢
        • 2019-05-13
        • 1970-01-01
        • 2018-04-26
        • 1970-01-01
        • 1970-01-01
        • 2017-10-28
        • 1970-01-01
        • 2018-07-03
        • 2017-12-10
        相关资源
        最近更新 更多