这是后续如何将包含 Unicode 代理项对的 JSON 编码数据转换为字符串? https://stackoverflow.com/questions/38106422/converting-to-emoji。在这个问题中,OP 有一个json.dumps()
- 带有表示为代理对的表情符号的编码文件 -\ud83d\ude4f
。他们在读取文件和正确翻译表情符号时遇到问题,并且正确的answer https://stackoverflow.com/a/38145581/1426065 was to json.loads()
文件中的每一行,以及json
模块将处理从代理对到(我假设是 UTF8 编码)表情符号的转换。
所以这是我的情况:假设我只有一个常规的 Python 3 unicode 字符串,其中有一个代理对:
emoji = "This is \ud83d\ude4f, an emoji."
我如何处理这个字符串以获得的表示emoji http://apps.timwhitlock.info/unicode/inspect?s=%F0%9F%99%8F出来了吗?我希望得到这样的东西:
"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
set to en_US.UTF-8
。我已经在命令行上的 Python 解释器中以及在 Sublime Text 中运行的 IPython 中运行了这些示例 - 似乎没有任何差异。