dongpangzan6425 2014-12-04 15:07 采纳率: 100%
浏览 828
已采纳

如何在Go中将所有编码都转换为UTF 8?

我正在通过 IMAP 下载消息。接下来,我将解析消息添加到 MongoDB 中,但我遇到了一个问题,因为 MongoDB 只支持 UTF 8, 我想把所有编码都转换成 UTF 8的话该怎么做?

我知道可以转换为二进制,但我必须有正常的文本,因为我必须在数据库中搜索短语。除非——我可以搜索二进制的正常文本吗?

  • 写回答

3条回答 默认 最新

  • doulierong0334 2014-12-04 15:37
    关注

    I'm using the go-charset project to do this: https://code.google.com/p/go-charset/

    It's pretty straightforward, you create a reader from a charset and it translates to utf-8 automatically. example from the library:

    r, err := charset.NewReader(strings.NewReader("\xa35 for Pepp\xe9"), "latin1")
    if err != nil {
        log.Fatal(err)
    }
    result, err := ioutil.ReadAll(r)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s
    ", result)  //outputs £5 for Peppé
    

    Now, in my case I know the charset because it comes from web pages and I read the headers/meta tags. If you need to detect the charset automatically by heuristics, you'll need another library for that, such as this one: https://github.com/saintfish/chardet

    I haven't used it but it also looks pretty simple to use:

    detector := chardet.NewTextDetector()
    result, err := detector.DetectBest(some_text)
    if err == nil {
        fmt.Printf(
            "Detected charset is %s, language is %s",
            result.Charset,
            result.Language)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助