Python 如何压缩字符串并使用 zlib 取回字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4845339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you compress a string, and get a string back using zlib?
提问by Quixotic
I am trying to utilize Zlib for text compression.
我正在尝试利用 Zlib 进行文本压缩。
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 Sso that I can decompress Tbut in a different program.
例如,我有一个字符串,T='blah blah blah blah'我需要为这个字符串压缩它。我正在使用S=zlib.compress(T)它来压缩它。现在我想要的是获得 的非二进制形式,S以便我可以T在不同的程序中解压缩。
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.
请建议您是否知道任何其他压缩方法可以提供与上述代码一致的更好结果。
回答by Tim Pietzcker
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.zlibso that program 2 can later retrieve and decompress it.
这会将压缩的字符串保存在一个名为的文件中,temp.zlib以便程序 2 稍后可以检索和解压缩它。
Program 2:
方案二:
with open("temp.zlib", "rb") as myfile:
S = myfile.read()
T = zlib.decompress(S)

