Python - 解码错误('ascii' 编解码器无法解码位置 19 中的字节 0x94 ......)

Python - Decoding Error ('ascii' codec can't decode byte 0x94 in position 19.....)

你好 :) 我有一个很大的 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 不是很陌生,但是 format/coding 问题一直是我最大的弱点:(

拜托,你能帮帮我吗?

谢谢!!!

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

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 字符。所以无论字节串 bs 是什么,bs.decode('Latin1').encode('Latin1') 都只是 bs.

的副本

最后,如果你真的需要过滤掉所有非ascii字符,你可以使用解码的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()