【问题标题】:How to decompress text in Python that has been compressed with gzip?如何在 Python 中解压缩已用 gzip 压缩的文本?
【发布时间】:2018-09-24 11:56:35
【问题描述】:

如何在 Python 3 中解压缩已用 gzip 压缩并转换为 base 64 的文本字符串?

例如文字:

EgAAAB+LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA==

应该转换为:

这是一些文字

以下C# 代码成功地做到了这一点:

var gzBuffer = Convert.FromBase64String(compressedText);

using (var ms = new MemoryStream()) {
    int msgLength = BitConverter.ToInt32(gzBuffer, 0);
    ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

    var buffer = new byte[msgLength];

    ms.Position = 0;
    using (var zip = new GZipStream(ms, CompressionMode.Decompress)) {
        zip.Read(buffer, 0, buffer.Length);
    }

    return Encoding.UTF8.GetString(buffer);
}

【问题讨论】:

  • 谢谢。每当我使用 base64 然后 zlib.decompress 解压缩数据时出现错误 -3:不正确的标头检查
  • module-base64module-gzip 感兴趣

标签: python python-3.x gzip compression gzipstream


【解决方案1】:

您可以使用gzipbase64 模块。

>>> import gzip
>>> import base64

>>> s = 'EgAAAB+LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA=='
>>> gz = base64.b64decode(s)
>>> gz
b'\x12\x00\x00\x00\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\x0b\xc9\xc8,V\x00\xa2\xe2\xfc\xdcT\x05\x85\x92\xd4\x8a\x12\x00\xbd\x9f_\xdf\x12\x00\x00\x00'

# If you need the length
import struct
# Unpacks binary encoded 4 byte integer (assume native byte order)
# Only select first four bytes with [:4] slice
>>> struct.unpack('i', gz[:4])[0]
18

# Skip length value with [4:] slice
>>> gzip.decompress(gz[4:]).decode('UTF8')
'This is some  text'

【讨论】:

  • 谢谢。需要跳过的 4 字节整数是什么?在尝试解决问题时,这似乎是我的问题。
  • 这是已经在初始文本中还是由 base64.b64decode(...) 引入的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2012-02-12
  • 2011-01-26
相关资源
最近更新 更多