本文介绍了如何在使用gzip压缩的Python中解压缩文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python 3中解压缩由gzip压缩并转换为base 64的文本字符串?
How can you decompress a string of text in Python 3, that has been compressed with gzip and converted to base 64?
例如,文本:
EgAAAB + LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA ==
应转换为:
这是一些文字
以下 C#
代码成功完成了此操作:
The following C#
code successfully does this:
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);
}
推荐答案
您可以使用 gzip
和 base64
模块.
>>> 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'
这篇关于如何在使用gzip压缩的Python中解压缩文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!