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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?