你好:)我有一个大的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不是很新,但格式/编码问题一直是我最大的弱点:(
拜托,你能帮帮我吗?
谢谢!!!
答案 0 :(得分:2)
首先,没有理由解码任何东西立即以原始字节写回来。因此,更简单(更强大)的实现可能是:
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()