这是Converting to Emoji的后续内容。在那个问题中,OP 有一个json.dumps()
-encoded 文件,其中的表情符号表示为代理对 - \ud83d\ude4f
。他/她在读取文件和正确翻译表情符号时遇到问题,正确答案是json.loads()
文件中的每一行,json
模块将处理从代理对转换回(我假设是 UTF8 编码的)表情符号。
所以这是我的情况:假设我只有一个普通的 Python 3 unicode 字符串,其中有一个代理对:
emoji = "This is \ud83d\ude4f, an emoji."
如何处理此字符串以从中获取表情符号的表示形式?我正在寻找这样的东西:
"This is , an emoji."
# or
"This is \U0001f64f, an emoji."
我试过了:
print(emoji)
print(emoji.encode("utf-8")) # also tried "ascii", "utf-16", and "utf-16-le"
json.loads(emoji) # and `.encode()` with various codecs
通常我会收到类似于UnicodeEncodeError: XXX codec can't encode character '\ud83d' in position 8: surrogates no allowed
.
我在 Linux 上运行 Python 3.5.1,$LANG
设置为en_US.UTF-8
. 我已经在命令行的 Python 解释器和在 Sublime Text 中运行的 IPython 中运行了这些示例——似乎没有任何区别。