【问题标题】:GO encoding/decodingGO编码/解码
【发布时间】:2021-07-13 22:43:20
【问题描述】:

我正在使用 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)

【问题讨论】:

标签: go decode encode


【解决方案1】:

我不确定@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

同样,与链接帖子中的评论相同:在投入过多精力尝试修复损坏的文本之前,您可能想尝试修复以这种奇怪方式进行编码的代码部分。

【讨论】:

    猜你喜欢
    • 2014-12-27
    • 2012-01-10
    • 1970-01-01
    • 2020-12-15
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多