在 Python 中将 Unicode 转义为表情符号

Escaped Unicode to Emoji in Python

我正在尝试将 Escaped Unicode 转换为 Emojis。

示例:

>>> emoji = ""
>>> emoji_text = "\ud83d\ude00"
>>> print(emoji)

>>> print(emoji_text)
\ud83d\ude00

我想打印

而不是“\ud83d\ude00”

我发现了一个简单但不实用的技巧:

>>> import json
>>> json.loads('"\ud83d\ude00"')
''

除了字符串中需要双引号外,您的示例与 JSON 的 ensure_ascii=True 字符串输出很接近。它包含 U+FFFF 以上 Unicode 字符的 Unicode 转义 high/low 代理项。

请注意 unicode-escape 编解码器不能单独用于转换。它将创建一个带有代理项的 Unicode 字符串,这是非法的。您将无法打印或编码序列化字符串。

>>> s = "\ud83d\ude00"
>>> s = s.encode('ascii').decode('unicode-escape')
>>> s
'\ud83d\ude00'
>>> print(s)  # UnicodeEncodeError: surrogates not allowed

使用 surrogatepass 错误处理程序和 utf-16 编解码器,您可以撤消代理并正确解码字符串。请注意,这也将解码非代理转义码:

>>> s = "Hello\u9a6c\u514b\ud83d\ude00"
>>> s.encode('ascii').decode('unicode-escape').encode('utf-16', 'surrogatepass').decode('utf-16')
'Hello马克'

旧的解决方案:

以下代码将用它们的 Unicode 代码点替换 Unicode 代理项。如果您有其他非代理 Unicode 转义,它也会用它们的代码点替换它们。

import re

def process(m):
    '''process(m) -> Unicode code point

    m is a regular expression match object that has groups below:
     1: high Unicode surrogate 4-digit hex code d800-dbff
     2: low  Unicode surrogate 4-digit hex code dc00-dfff
     3: None
    OR
     1: None
     2: None
     3: Unicode 4-digit hex code 0000-d700,e000-ffff
    '''
    if m.group(3) is None:
        # Construct code point from UTF-16 surrogates
        hi = int(m.group(1),16) & 0x3FF
        lo = int(m.group(2),16) & 0x3FF
        cp = 0x10000 | hi << 10 | lo
    else:
        cp = int(m.group(3),16)
    return chr(cp)

s = "Hello\u9a6c\u514b\ud83d\ude00"
s = re.sub(r'\u(d[89ab][0-9a-f]{2})\u(d[cdef][0-9a-f]{2})|\u([0-9a-f]{4})',process,s)
print(s)

输出:

Hello马克