[英]GO encoding/decoding
我正在使用 python。 但是现在,我需要修复 Go 错误。 我有这样的字符串:
<!-- \\xd0\\xbf\\xd0\\xbb\\xd0\\xb0\\xd1\\x82\\xd0\\xb5\\xd0\\xb6\\xd0\\xb5\\xd0\\xb9-->\\n \\n \\n <guarantees>\\n
如何使它正确和可读? 如果它是 Python,我会使用decode('unicode-escape')
。 但是我应该在 Go 中使用什么?
更新
我已经编辑了描述。 有双反斜杠
更新 1
我遵循了答案https://stackoverflow.com/a/67172057/11029221 中的建议,并修复了以这种错误方式进行编码的代码部分。 但我发现在 GO 中你可以像这样修复这样的文本:
a := `\\xd0\\xb5\\xd0\\xb6\\xd0\\xb5\\xd0\\xb9-->\\n\\n\\n<guarantees>\\n`
a = strconv.Quote(a)
a = strings.ReplaceAll(a, `\\\\`, `\`)
unquoted, err := strconv.Unquote(a)
if err != nil {
println(err)
}
str := []byte(unquoted)
for len(str) > 0 {
r, size := utf8.DecodeLastRune(str)
out = string(r) + out
str = str[:len(str)-size]
}
fmt.Printf("%s", out)
我不确定@melpomene 的“知道他们在做什么”的标准是什么,但以下解决方案以前有效,例如用于解码损坏的希伯来语文本:
("\\u00c3\\u00a4"
.encode('latin-1')
.decode('unicode_escape')
.encode('latin-1')
.decode('utf-8')
)
产出
'ä'
其工作原理如下:
The string that contains only ascii-characters '\', 'u', '0', '0', 'c', etc. is converted to bytes using some not-too-crazy 8-bit encoding (doesn't really matter which one, as long as it treats ASCII characters properly)
Use a decoder that interprets the '\u00c3' escapes as unicode code point U+00C3 (LATIN CAPITAL LETTER A WITH TILDE, 'Ã'). From the point of view of your code, it's nonsense, but this unicode code point has the right byte representation when again encoded with ISO-8859-1/'latin-1', so...
encode it again with 'latin-1'
Decode it "properly" this time, as UTF-8
同样,与链接帖子中的评论相同:在投入太多精力尝试修复损坏的文本之前,您可能想要尝试修复以这种奇怪方式进行编码的代码部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.