如何压缩字符串,并使用zlib取回字符串? [英] How do you compress a string, and get a string back using zlib?
问题描述
我正在尝试使用Zlib进行文本压缩。
例如,我有一个字符串 T ='blah blah blah blah'
我需要为这个字符串压缩它。我正在使用 S = zlib.compress(T)
进行压缩。现在,我想要的是获取 S
的非二进制形式,以便我可以解压缩 T
,但使用另一种方式
谢谢!
编辑:我想我有一种解决自己想要的方法。方法如下:
import zlib,base64
text ='STACK OVERFLOW堆栈溢出堆栈溢出堆栈溢出堆栈溢出堆栈溢出堆栈溢出堆栈溢出堆栈溢出堆栈溢出'
code = base64.b64encode(zlib.compress(text,9))
打印代码
其中给出:
eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU =
现在,我可以将此代码复制到另一个程序中,以获取原始变量:
导入zlib,base64
s ='eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU ='
data = zlib.decompress(base64.b64decode(s))
打印数据
请提出建议,如果您知道其他压缩方法会产生更好的压缩效果,
程序1:
T ='等等等等
S = zlib.com使用open( temp.zlib, wb)作为myfile的press(T)
:
myfile.write(S)
这会将压缩后的字符串保存在名为 temp.zlib
的文件中,以便程序2以后可以对其进行检索和解压缩。 / p>
程序2:
打开( temp.zlib, rb)作为myfile:
S = myfile.read()
T = zlib.decompress(S)
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.
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)
这篇关于如何压缩字符串,并使用zlib取回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!