【问题标题】:Decoding gb-2312 file in colab在 colab 中解码 gb-2312 文件
【发布时间】:2021-02-24 01:09:05
【问题描述】:

我正在尝试在 Colab 中打开一个使用 gb-2312 编码的文件。这是我成功在我的 IDE 中运行以读取和解码的代码:

file = open(r'file.txt')
opened = file.read()
decoded = opened.encode('latin1').decode('gb2312')
print(decoded)

当我在 colab 中运行此代码时,我收到以下错误:

'utf-8' codec can't decode byte 0xc6 in position 67: invalid continuation byte

但如果不先使用 read() 或 list() 就无法解码,否则会出现以下错误:

'_io.TextIOWrapper' object has no attribute 'encode'

这似乎是第 22 条规则。这是 Colab 的错误还是有更好的方法来解决这个问题?

【问题讨论】:

    标签: utf-8 google-colaboratory gb2312


    【解决方案1】:

    打开文件时的默认值为rt(读取,文本模式)并使用locale.getpreferredencoding(False) 返回的特定于操作系统的默认编码。使用encoding 参数覆盖默认值(似乎是utf-8):

    with open('file.txt', encoding='gb2312') as file:
        data = file.read()
    

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2020-07-15
      • 2014-12-06
      • 2018-11-26
      相关资源
      最近更新 更多