[英]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.