问题描述
我正在使用 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','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
同样,与链接帖子中的评论相同:在投入太多精力尝试修复损坏的文本之前,您可能想要尝试修复以这种奇怪方式进行编码的代码部分。
>