【问题标题】:Gzip Python 3 vs Gzip Python 2Gzip Python 3 与 Gzip Python 2
【发布时间】:2017-02-24 17:56:50
【问题描述】:

问题:我有一个旧代码,它使用 Py2 'str' 并且使用 gzip 压缩该字符串,我希望从从 Py3 中的同一字符串 gzip 但我无法使其工作。

Python 2 代码

#input_buffer is a str 
string_buffer = StringIO()
gzip_file = GzipFile(fileobj=string_buffer, mode='w', compresslevel = 6)
gzip_file.write(input_buffer)
gzip_file.close()
out_buffer = string_buffer.getvalue()

现在我尝试在 Py3 中迁移相同的代码并期望得到完全相同的结果

Python 3 代码

#input_buffer is a the exact same string that I have on Py2
string_buffer = BytesIO()
gzip_file = GzipFile(fileobj=string_buffer, mode=u'w', compresslevel = 6)
gzip_file.write(bytes(input_buffer, 'utf-8'))
gzip_file.close()
out_buffer = string_buffer.getvalue()

我注意到,一旦我将 'str' 设为 Bytes 数组,它就会添加额外的字符,这些字符随后会被压缩并出现在最终结果中,即使在我解码代码之后也是如此。此外,没有“忽略”标志的解码也会失败,因为某些字符比预期的要大。

我的问题有什么解决办法吗?

总结一下:我有一个 str 并且我希望 Py2 和 Py3 gzip 压缩具有完全相同的输出。实际上,至少从我的尝试来看,它不起作用。

谢谢

我看到的一个问题是,即使它们具有相同的值,它们的表示方式也不同,我希望结果看起来像在 Python2 中的唯一方法

Python3
input_buffer='+\n\x01I\x12Default_Source©$c1f33163-ff63-13e6-bd74-d90d67f22ac4Ñ\x06\x80\x9dº\x9fÌVÐ\x07\x02Ë\x08\n\x01)$'
out_buffer =b'\x1f\x8b\x08\x00\x00x\xb0X\x02\xff\xd3\xe6b\xf4\x14rIMK,\xcd)\x89\x0f\xce/-JN=\xb4R%\xd90\xcd\xd8\xd8\xd0\xccX7-\rH\x18\x1a\xa7\x9a\xe9&\xa5\x98\x9b\xe8\xa6X\x1a\xa4\x98\x99\xa7\x19\x19%&\x9b\x1c\x9e\xc8v\xa8\xe1\xd0\xdcC\xbb\x0e\xcd?\xdc\x13vx\x02;\xd3\xe1n\x0e.FM\x15\x00\x03&\xcf\x15S\x00\x00\x00'

Python2
input_buffer='+\n\x01I\x12Default_Source\xa9$c1f33163-ff63-13e6-bd74-d90d67f22ac4\xd1\x06\x80\x9d\xba\x9f\xccV\xd0\x07\x02\xcb\x08\n\x01)$'
out_buffer ='\x1f\x8b\x08\x00\xae|\xb0X\x02\xff\xd3\xe6b\xf4\x14rIMK,\xcd)\x89\x0f\xce/-JN]\xa9\x92l\x98fllhf\xac\x9b\x96\x06$\x0c\x8dS\xcdt\x93R\xccMtS,\rR\xcc\xcc\xd3\x8c\x8c\x12\x93M.\xb25\xcc\xdd5\xffL\xd8\x05v\xa6\xd3\x1c\\\x8c\x9a*\x00\xe9l\xf0\xeaJ\x00\x00\x00'

【问题讨论】:

  • 你能举一个产生问题的input_buffer的例子吗?
  • gzip 文件是二进制文件。将字节 string_buffer 解码为 utf-8 是没有意义的。
  • @onlynone 我发布了一个示例。即使它们看起来不同,这也是在 Py3 和 Py2 中表示相同字符串的方式,但至少对于 out_buffer,我只想看到 Py2 中的结果
  • @onlynone 我放错了例子,我会尽快放正确的
  • 在 Python2 中 input_buffer 是字节,你的字符是 latin1 编码的。在 Python3 中,您有一个带有 unicode 的字符串,您使用 utf8 对其进行编码。要获得相同的结果,您必须在 python3 中编码为 latin1:gzip_file.write(bytes(input_buffer, 'latin1'))

标签: python python-3.x gzip python-2.x


【解决方案1】:

在Python2中input_buffer是字节,字符编码是latin1。在 Python3 中,您有一个带有 unicode 的字符串,您将其编码为 utf-8。要获得相同的结果,您必须在 Python 3 中编码为 latin1:

input_buffer = '+\n\x01I\x12Default_Source©$c1f33163-ff63-13e6-bd74-d90d67f22ac4Ñ\x06\x80\x9dº\x9fÌVÐ\x07\x02Ë\x08\n\x01)$'
string_buffer = BytesIO()
with GzipFile(fileobj=string_buffer, mode='w', compresslevel=6) as gzip_file:
    gzip_file.write(bytes(input_buffer, 'latin1'))
out_buffer = string_buffer.getvalue()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多