【发布时间】:2018-09-18 22:55:35
【问题描述】:
XKCD 的 API 存在一些问题和奇怪的编码问题。
Minor encoding issue with xkcd alt texts in chat
解决方案(在 Python 中)是将其编码为 latin1,然后解码为 utf8,但如何在 Swift 中做到这一点?
测试字符串:
"Be careful\u00e2\u0080\u0094it's breeding season"
预期输出:
Be careful—it's breeding season
Python(来自上面的链接):
import json
a = '''"Be careful\u00e2\u0080\u0094it's breeding season"'''
print(json.loads(a).encode('latin1').decode('utf8'))
这是如何在 Swift 中完成的?
let strdata = "Be careful\\u00e2\\u0080\\u0094it's breeding season".data(using: .isoLatin1)!
let str = String(data: strdata, encoding: .utf8)
这行不通!
【问题讨论】:
-
对不起,我不知道 Swift,所以我不知道该建议什么。 Latin1 “技巧”之所以有效,是因为对于 0 n n 编码为 Latin1 中值为
n的字节。也就是说,b''.join([chr(i).encode('latin1') for i in range(256)]) == bytes(range(256))是 True。 -
您对 Swift 示例的预期结果是什么?
-
@PM2Ring 那么这对这部漫画有用吗? xkcd.com/1814/info.0.json
-
@MartinR 更新以使其在 Swift 中的预期输出和正确的字符串更加清晰
-
当然。我得到
♫ When the spacing is tight / And the difference is slight / That's a moiré ♫
标签: python swift encoding utf-8 character-encoding