【问题标题】:Python - Decoding Error ('ascii' codec can't decode byte 0x94 in position 19.....)Python - 解码错误('ascii' 编解码器无法解码位置 19 的字节 0x94 .....)
【发布时间】:2017-12-18 16:02:13
【问题描述】:

你好 :) 我有一个大的 bin 文件,它已被 gzip 压缩(所以它是 blabla.bin.gz)。

我需要解压并写入一个ASCII格式的txt文件。 这是我的代码:

import gzip

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f:   

    file_content = f.read()
    file_content.decode("ascii")
    output = open("new_file.txt", "w", encoding="ascii")
    output.write(file_content)
    output.close()

但我得到了这个错误:

file_content.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 19: ordinal not in range(128)

我对 Python 并不陌生,但格式/编码问题一直是我最大的弱点 :(

拜托,你能帮帮我吗?

谢谢!!!

【问题讨论】:

  • 考虑过 gzip 压缩文件可能是 UTF8 或 unicode 或其他任何格式的文件吗?你能检查一下吗? 128位ASCII没有处理的东西?只是为了咯咯笑:尝试encoding='utf-8', 或只是file_content.decode("utf-8") - 更好地习惯 utf-8 - 现在它是一种默认值。
  • 你应该改用这个:docs.python.org/3/library/binascii.html
  • file_content.decode('cp1252') 有效吗? 0x94 是 cp1252 中的右大括号双引号,是 Windows 系统上常见的编码。
  • @PatrickArtner (1) ValueError: 二进制模式不支持参数“编码”(我在二进制模式下使用“rb”); (2) 我必须创建一个 ascii 文件。 :(
  • @usr2564301:注意,cp1252 接近 Latin1 但不是,只有 Latin1 保证 decode/encode 是无操作的。

标签: python ascii decode encode gzip


【解决方案1】:

首先,没有理由对任何内容进行解码以立即将其以原始字节写回。所以一个更简单(也更健壮)的实现可能是:

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f:   

    file_content = f.read()
    with open("new_file.txt", "wb") as output:  # just directly write raw bytes
        output.write(file_content)

如果你真的想解码但不确定编码,你可以使用 Latin1。每个字节在 Latin1 中都是有效的,并以相同值的 unicode 字符进行翻译。所以无论bsbs.decode('Latin1').encode('Latin1')是什么字节串都只是bs的一个副本。

最后,如果你真的需要过滤掉所有非ascii字符,你可以使用decode的error参数:

file_content = file_content.decode("ascii", errors="ignore") # just remove any non ascii byte

或:

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f:   

    file_content = f.read()
    file_content = file_content.decode("ascii", errors="replace") #non ascii chars are
                                            # replaced with the U+FFFD replacement character
    output = open("new_file.txt", "w", encoding="ascii", errors="replace") # non ascii chars
                                                      # are replaced with a question mark "?"
    output.write(file_content)
    output.close()

【讨论】:

  • 谢谢,但它给了我这个错误:output.write(file_content) TypeError: write() argument must be str, not bytes 所以基本上它仍然将file_content 视为一个 bin 文件......但是为什么呢?
  • @inTaowetrust:在第一个解决方案中,file_content 是一个字节字符串,输出文件以二进制模式打开("wb"),而在第二个解决方案中,file_content 成为一个 unicode 字符串和文件以文本模式打开。等等...我忘记分配给file_content :-(。请看我的编辑
猜你喜欢
  • 1970-01-01
  • 2013-12-05
  • 2011-06-29
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2016-02-13
  • 2015-01-14
相关资源
最近更新 更多