unicode - 如何在 Go 中从编码转换为 UTF-8?

标签 unicode go

我正在进行一个项目,我需要将文本从编码(例如 Windows-1256 阿拉伯语)转换为 UTF-8。

如何在 Go 中执行此操作?

最佳答案

您可以使用 the encoding package ,其中包括通过包 golang.org/x/text/encoding/charmap 支持 Windows-1256(在下面的示例中,导入此包并使用 charmap.Windows1256而不是 japanese.ShiftJIS)。

这是一个简短的示例,它将日语 UTF-8 字符串编码为 ShiftJIS 编码,然后将 ShiftJIS 字符串解码回 UTF-8。不幸的是,它在 Playground 上不起作用,因为 Playground 没有“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

关于unicode - 如何在 Go 中从编码转换为 UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32518432/

相关文章:

python - python加载json时,如何将str转成unicode,才能打印汉字?

java - String.getBytes ("ISO-8859-1") 在 OS X 上给我 16 位字符

python - ElementTree Unicode 编码/解码错误

php - 如何搜索显示为十进制数字字符引用 (NCR) &#xxxxx 的 MySQL 条目?

mongodb - 在 mongodb 记录中使用 time.Time

Linux 和 Windows 上的 Python sys.maxint、sys.maxunicode

json - 使用 json.Decoder 解码顶级 JSON 数组

go - 函数调用中的类型参数 panic

go - 多个 go 项目并共享一个 vendor 目录(在 1.11 之前的 go 中)

windows - 从 Windows 上的 Go *net.UDPConn 获取 syscall.Handle?