美文网首页
golang 字符编码转换

golang 字符编码转换

作者: 夜空中乄最亮的星 | 来源:发表于2021-05-08 22:13 被阅读0次

1.对于已知的编码

就以GBK转utf-8为例,主要是引入golang.org/x/text
比较简单直接上代码

import (
    "fmt"
    //_ "golang.org/x/text"
    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
    "io/ioutil"
    "net/http"
)

func main(){
    //请求页面,获取
     response,_:=http.Get("http://www.xxx.com")
    //编码转换
    reader := transform.NewReader(response.Body, simplifiedchinese.GBK.NewDecoder())
    bytes, err := ioutil.ReadAll(reader)
    if err !=nil {
        panic(err)
    }
    fmt.Printf("%s",bytes)
}

2.对于不确定的编码,例如html页面内容

使用golang.org/x/net/html包自动检测

package main
//import有点复杂 这是goland自动生成的,用不上的去掉也ok
import (
    "bufio"
    "fmt"
    _ "golang.org/x/net/html"
    "golang.org/x/net/html/charset"
    _ "golang.org/x/text"
    "golang.org/x/text/encoding"
    _ "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
    "io"
    "io/ioutil"
    "net/http"
)

func main(){
    //请求页面,获取
     response,_:=http.Get("http://www.xxx.com")
    //编码转换,自动检测网页编码
    bodyReader := bufio.NewReader(response.Body)
    charset:=determinePageEncoding(bodyReader)
    reader := transform.NewReader(response.Body, charset.NewDecoder())
    bytes, err := ioutil.ReadAll(reader)
    if err !=nil {
        panic(err)
    }
    fmt.Printf("%s",bytes)
}


//检测html页面编码
func determinePageEncoding(r *bufio.Reader)encoding.Encoding{
//使用peek读取十分关键,只是偷看一下,不会移动读取位置,否则其他地方就没法读取了
    bytes, err := r.Peek(1024)
    if err !=nil {
        log.Printf("Fetcher error: %v\n",err)
        return unicode.UTF8
    }
    e, _, _ := charset.DetermineEncoding(bytes, "")
    return e
}

相关文章

  • golang 字符编码转换

    1.对于已知的编码 就以GBK转utf-8为例,主要是引入golang.org/x/text包比较简单直接上代码 ...

  • golang字符串重新编码

    golang 字符串重新编码 golang 字符串重新编码//byte decode/*** function ...

  • Golang字符编码转换 - gcharset

    文章来源:https://goframe.org/encoding/gcharset/index gcharset...

  • 部分知识点

    chr(编码值) - 将字符编码转换成字符 ord(字符) - 获取字符对应的编码值 可以将字符编码放到字符串中便...

  • Pytho基础知识:字符编码

    阅读目录一、字符编码 1、什么实字符编码:将人识别的字符转换成计算机能识别的01,而转换的过程或者规则就是字符编码...

  • 常用函数记录

    字符串编码转换函数:

  • Python正式课第十三天

    一、文件操作与字符编码 1. 字符编码 编码 将字符转换为对应的二进制序列的过程叫做字符编码(字符->二进制01)...

  • Unicode编码和多字节编码

    wchar_t:unicode编码的字符char:多字节编码的字符TCHAR:根据环境转换字符类型的字符 "hel...

  • js 16进制转中文

    转换为中文字符串 转换为unicode编码

  • GoLang 字符转换

    字符转换 目标:使用Go语言,函数LetterChanges(str)将传递str参数,并使用以下算法对其进行修改...

网友评论

      本文标题:golang 字符编码转换

      本文链接:https://www.haomeiwen.com/subject/pmspdltx.html