Contents

go第三方库-cs.opensource.google.go.x.text

Contents

godoc

官网

用于文本处理的补充 Go 库,其中许多涉及 Unicode

默认go读写文件都是按照utf-8的,且标准库不提供修改编码方式的api(不同于pthon可以在使用open函数打开文件的时候直接指定encoding),这个库提供了修改读写文件编码的api

常见用法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
    "io/ioutil"
    "os"
    "strings"
    "golang.org/x/text/transform"
    "golang.org/x/text/encoding/charmap"
)

func main() {
    str := "This is a string to be encoded in ISO-8859-1!"

    // 将UTF-8的字符串转换为ISO-8859-1编码
    sr := strings.NewReader(str)
    tr := transform.NewReader(sr, charmap.ISO8859_1.NewEncoder())

    // 读取转换后的数据
    buf, _ := ioutil.ReadAll(tr)

    // 写入文件
    ioutil.WriteFile("output.txt", buf, 0644)
}

对于标准库的io.Reader或者io.Writer(包括bufio里面的),我们都可以添加一个transform的Reader或者Writer来改变读写编码

 |