Use zlib.compress to compress strings. Use Zlib.decompress to extract strings. As follows
The code is as follows |
Copy Code |
#coding =utf-8 Import zlib s = "Hello Word, 00000000000000000000000000000000" Print Len (s) c = zlib.compress (s) Print Len (c) D = zlib.decompress (c) Print D |
Model Code 2:
The code is as follows |
Copy Code |
Import zlib message = ' witch which has which witches wrist ' compressed = zlib.compress (message) decompressed = zlib.decompress (compressed) print ' original: ', repr (message) print ' compressed: ', repr (compressed) print ' decompressed: ', repr (decompressed) output original: ' Witch which has which witches, wrist watch ' Compressed: ' Xx9c+xcf,ixcep (XCFXC8X04X92X19X89XC5PV9H4X15XC8+XCA,. Q (ox04xf2x00d?x0fx89 ' decompressed: ' witch which has which witches ' wrist ' |
If we want to extract the string, we can compress and decompress the file using Zlib.compressobj and Zlib.decompressobj.
code is as follows |
copy code |
Def compress (infile, DST, level=9): infile = open (infile, ' RB ') DST = ope N (DST, ' WB ') compress = Zlib.compressobj (level) data = infile.read (1024) br> while data: dst.write compress.compress (data) data = infile.read (1024) dst.write ( Compress.flush ()) Def decompress (infile, DST): infile = open (infile, ' RB ') & nbsp DST = open (DST, ' WB ') decompress = zlib.decompressobj () data = Infile.read ( 1024) while data: dst.write ( Decompress.decompress (data) data = infile.read (1024) Dst.write (Decompress.flush ()) |