如何在 Go 中从编码转换为 UTF-8?
时间:2023-04-15
浏览:465
作者:佚名
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《如何在 Go 中从编码转换为 UTF-8?》,这篇文章主要讲到golang等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
问题内容
我正在做一个项目,我需要将文本从编码(例如 Windows-1256 阿拉伯语)转换为 UTF-8。
我如何在 Go 中做到这一点?
正确答案
您可以使用编码包,其中包括通过包对 Windows-1256
的支持golang.org/x/text/encoding/charmap(在下面的示例中,导入此包并使用charmap.Windows1256代替japanese.ShiftJIS)。
这是一个简短的示例,它将日语 UTF-8 字符串编码为 ShiftJIS 编码,然后将 ShiftJIS 字符串解码回 UTF-8。不幸的是,它在操场上不起作用,因为操场没有“x”包。
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
"golang.org/x/text/encoding/japanese"
"golang.org/x/text/transform"
)
func main() {
// the string we want to transform
s := "浠婃棩銇�"
fmt.Println(s)
// --- Encoding: convert s from UTF-8 to ShiftJIS
// declare a bytes.Buffer b and an encoder which will write into this buffer
var b bytes.Buffer
wInUTF8 := transform.NewWriter(&b, japanese.ShiftJIS.NewEncoder())
// encode our string
wInUTF8.Write([]byte(s))
wInUTF8.Close()
// print the encoded bytes
fmt.Printf("%#v\n", b)
encS := b.String()
fmt.Println(encS)
// --- Decoding: convert encS from ShiftJIS to UTF8
// declare a decoder which reads from the string we have just encoded
rInUTF8 := transform.NewReader(strings.NewReader(encS), japanese.ShiftJIS.NewDecoder())
// decode our string
decBytes, _ := ioutil.ReadAll(rInUTF8)
decS := string(decBytes)
fmt.Println(decS)
}
在日文 StackOverflow 网站上有一个更完整的示例。文字是日语,但代码应该是不言自明的:https ://ja.stackoverflow.com/questions/6120
文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在 Go 中从编码转换为 UTF-8?》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
11.28
热门专题
