Go实战--go中编码转换(The way to go)
来源:互联网 发布:狸窝网络视频下载器 编辑:程序博客网 时间:2024/04/27 09:43
生命不止,继续 go go go !!!
编码问题在每种语言中都会遇到,尤其对于中国的码农来说,更是常见的问题,因为我们的汉字有一点点特别。所以需要一些自己的编码,这就需要进行一些适当的转换。
例如,C++开发中,我们经常会用到wstring与string的互相转换。
所以,今天就介绍一下Golang中的编码转换,我们介绍一个库:mahonia
mahonia
Mahonia is a character-set conversion library implemented in Go. All data is compiled into the executable; it doesn’t need any external data files.
Mahonia is now deprecated. I recommend using the standard package at golang.org/x/text/encoding, possibly along with golang.org/x/net/charset
看到了作用了吧,但是,细心的朋友确实发现了上面英文描述的重点deprecated,已经被弃用了,但是我还是简单的介绍一下吧,共同学习。
下载源码
https://code.google.com/archive/p/mahonia/source/default/source
下载,解压,然后把mahonia文件夹放到GOPATH的src文件夹下即可(这里根据实际情况进行)。
读写文件
新建一个text.txt,键入内容“大宝剑”
写程序:
package mainimport ( "bufio" "fmt" "log" "mahonia" "os" "strings" "time")func main() { //生成日志文件 t := time.Now() filepath := "./log_" + strings.Replace(t.String()[:19], ":", "_", 3) + ".txt" file, err := os.OpenFile(filepath, os.O_CREATE, 0666) if err != nil { log.Fatal("failed!") } defer file.Close() wFile := bufio.NewWriter(file) wFile.WriteString(readfile()) wFile.Flush()}func readfile() string { f, err := os.Open("test.txt") if err != nil { return err.Error() } defer f.Close() buf := make([]byte, 1024) decoder := mahonia.NewDecoder("gb18030") if decoder == nil { fmt.Println("编码不存在!") return "编码不存在!" } var str string = "" for { n, _ := f.Read(buf) if 0 == n { break } //解码为UTF-8 fmt.Println(string(buf[:n])) str += decoder.ConvertString(string(buf[:n])) fmt.Println(str) } return str}
阅读全文
1 0
- Go实战--go中编码转换(The way to go)
- Go实战--go中使用libphonenumber(The way to go)
- Go实战--go中使用cookie(The way to go)
- Go实战--go中使用rpc(The way to go)
- Go实战--go语言中执行shell脚本(The way to go)
- Go实战--go中使用google/protobuf(The way to go)
- Go实战--go中使用base64加密(The way to go)
- Go实战--go中使用hmac sha256(The way to go)
- Go实战--go中一些有用的代码片段(The way to go)
- Go实战--go中函数(function)和方法(method)的使用(The way to go)
- Go实战--go中函数递归(recursion)的使用(The way to go)
- The way to go !
- Go实战--golang新手入门常见错误(The way to go)
- Go实战--golang生成uuid(The way to go)
- Go实战--xml与json相互转换(The way to go)
- Go实战--net/http中JSON的使用(The way to go)
- Go实战--go语言操作sqlite数据库(The way to go)
- [读书笔记] The.Way.To.Go
- keil #pragma anon_unions
- DAY2 操作系统
- 51Nod-1349-最大值
- 关于Unity中Rigidbody组件的各个变量的含义
- 20170518 Django入门
- Go实战--go中编码转换(The way to go)
- sklearn SVM算法自动调优
- Spire.Doc for .NET 简介
- Windows防火墙阻止了远程调试
- android IPC学习(二) 创建多进程
- linux下aliax的作用
- SpringAop中使用@AspectJ注解
- angularJS自定义指令详解
- 获取某一天一周内所有的日期