Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you compress a string, and get a string back using zlib?

Tags:

I am trying to utilize Zlib for text compression.

For example I have a string T='blah blah blah blah' I need to compress it for this string. I am using S=zlib.compress(T) to compress it. Now what I want is to get the non-binary form of S so that I can decompress T but in a different program.

Thanks!

EDIT: I guess I got a method to solve what I wanted. Here is the method:

import zlib, base64 text = 'STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW ' code =  base64.b64encode(zlib.compress(text,9)) print code 

Which gives:

eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU= 

Now I can copy this code to a different program to get the original variable back:

import zlib, base64 s='eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU=' data = zlib.decompress(base64.b64decode(s)) print data 

Please suggest if you are aware of any other compression method which would give better results that are consistent with the above code.

like image 595
Quixotic Avatar asked Jan 30 '11 20:01

Quixotic


People also ask

How does zlib compress work?

zlib compressed data are typically written with a gzip or a zlib wrapper. The wrapper encapsulates the raw DEFLATE data by adding a header and trailer. This provides stream identification and error detection that are not provided by the raw DEFLATE data.

How do you compress and decompress a string in Python?

With the help of gzip. decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip. decompress(s) method. Return : Return decompressed string.

Does gzip use zlib?

zlib was adapted from the gzip code. All of the mentioned patents have since expired. The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams.


1 Answers

Program 1:

T = 'blah blah blah blah' S = zlib.compress(T) with open("temp.zlib", "wb") as myfile:     myfile.write(S) 

This saves the compressed string in a file called temp.zlib so that program 2 can later retrieve and decompress it.

Program 2:

with open("temp.zlib", "rb") as myfile:     S = myfile.read() T = zlib.decompress(S) 
like image 92
Tim Pietzcker Avatar answered Oct 21 '22 12:10

Tim Pietzcker