问题描述
我试图利用Zlib进行文本压缩。
I am trying to utilize Zlib for text compression.
例如,我有一个文本 T ='blah blah blah blah' code>我需要压缩它为我使用
S = zlib.compress(T)
现在我想要的是获得ASCII形式的 S
,以便我可以解压这个 T
,但在一个不同的程序。
谢谢,
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,
编辑:我想我有一个方法来解决这里的方式:
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
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
请注意,如果您知道任何其他压缩方法,可以提供更好的结果,同时保持一致。
推荐答案
计划1:
T = 'blah blah blah blah'
S = zlib.compress(T)
with open("temp.zlib", "wb") as myfile:
myfile.write(S)
这将压缩的字符串保存在一个名为 temp.zlib
的文件中,
This saves the compressed string in a file called temp.zlib
so that program 2 can later retrieve and decompress it.
Program 2:
打开(temp.zlib,rb)作为myfile:
S = myfile.read()
T = zlib.decompress(S)
with open("temp.zlib", "rb") as myfile: S = myfile.read()T = zlib.decompress(S)
这篇关于如何压缩文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!