Como faço para compactar gzip uma string em Python?
gzip.GzipFile
existe, mas isso é para objetos de arquivo - e quanto a strings simples?
python
compression
gzip
Bdfy
fonte
fonte
StringIO
mas não explica realmente como fazê-lo. Então, fazer essa pergunta aqui é totalmente válido, IMHO. No entanto, mais algumas tentativas antes de nos perguntar e nos contar sobre eles teriam sido legais.gzip string in python
e é muito razoável IMO. Deve ser reaberto.Respostas:
Se você quiser produzir uma
gzip
string binária totalmente compatível, com o cabeçalho, etc., você pode usargzip.GzipFile
junto comStringIO
:try: from StringIO import StringIO # Python 2.7 except ImportError: from io import StringIO # Python 3.x import gzip out = StringIO() with gzip.GzipFile(fileobj=out, mode="w") as f: f.write("This is mike number one, isn't this a lot of fun?") out.getvalue() # returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff\x0b\xc9\xc8,V\x00\xa2\xdc\xcc\xecT\x85\xbc\xd2\xdc\xa4\xd4"\x85\xfc\xbcT\x1d\xa0X\x9ez\x89B\tH:Q!\'\xbfD!?M!\xad4\xcf\x1e\x00w\xd4\xea\xf41\x00\x00\x00'
fonte
f = gzip.GzipFile(StringIO.StringIO(text)); result = f.read(); f.close(); return result
import zlib; my_string = "hello world"; my_bytes = zlib.compress(my_string.encode('utf-8')); my_hex = my_bytes.hex(); my_bytes2 = bytes.fromhex(my_hex); my_string2 = zlib.decompress(my_bytes); assert my_string == my_string2;
A maneira mais fácil é a
zlib
codificação :compressed_value = s.encode("zlib")
Então você descompacta com:
plain_string_again = compressed_value.decode("zlib")
fonte
s
é um objeto 2.x do Python do tipostr
.s.encode('rot13')
,s.encode( 'base64' )
plain_string_again = compressed_value.decode("zlib")
str
em Python 3) e strings de byte (tipobytes
).str
os objetos têm umencode()
método que retorna umbytes
objeto e osbytes
objetos têm umdecode()
método que retorna astr
. Ozlib
codec é especial porque pode ser convertido debytes
parabytes
, portanto, não se encaixa nessa estrutura. Você pode usarcodecs.encode(b, "zlib")
ecodecs.decode(b, "slib")
para umbytes
objetob
.Versão Python3 da resposta de Sven Marnach de 2011:
import gzip exampleString = 'abcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijmortenpunnerudengelstadrocksklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvabcdefghijklmnopqrstuv123' compressed_value = gzip.compress(bytes(exampleString,'utf-8')) plain_string_again = gzip.decompress(compressed_value)
fonte
zlib
ainda é usado,gzip
realmente usazlib
, consulte: docs.python.org/3/library/zlib.html e docs.python.org/3/library/gzip.html#module-gzipPara quem deseja compactar um dataframe Pandas no formato JSON:
Testado com Python 3.6 e Pandas 0.23
import sys import zlib, lzma, bz2 import math def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "%s %s" % (s, size_name[i]) dataframe = pd.read_csv('...') # your CSV file dataframe_json = dataframe.to_json(orient='split') data = dataframe_json.encode() compressed_data = bz2.compress(data) decompressed_data = bz2.decompress(compressed_data).decode() dataframe_aux = pd.read_json(decompressed_data, orient='split') #Original data size: 10982455 10.47 MB #Encoded data size: 10982439 10.47 MB #Compressed data size: 1276457 1.22 MB (lzma, slow), 2087131 1.99 MB (zlib, fast), 1410908 1.35 MB (bz2, fast) #Decompressed data size: 10982455 10.47 MB print('Original data size: ', sys.getsizeof(dataframe_json), convert_size(sys.getsizeof(dataframe_json))) print('Encoded data size: ', sys.getsizeof(data), convert_size(sys.getsizeof(data))) print('Compressed data size: ', sys.getsizeof(compressed_data), convert_size(sys.getsizeof(compressed_data))) print('Decompressed data size: ', sys.getsizeof(decompressed_data), convert_size(sys.getsizeof(decompressed_data))) print(dataframe.head()) print(dataframe_aux.head())
fonte
s = "a long string of characters" g = gzip.open('gzipfilename.gz', 'w', 5) # ('filename', 'read/write mode', compression level) g.write(s) g.close()
fonte