How to compress a text?

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I am trying to utilize Zlib for text compression.

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

EDIT: I guess I got a method to solve it here is the way:

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 program 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 while consistent to the same manner.

回答1:

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) 


回答2:

Use pickle. This allows you to save a python object to a stream (like a file) which you can then unpickle in your other program (you could also stream over TCP or what have you; pickle serializes the data).

http://docs.python.org/library/pickle.html



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!