我如何在Python中压缩string?
我如何在Python中压缩string?
gzip.GzipFile
存在,但这是文件对象 – 用纯string呢?
从http://docs.python.org/library/archiving.html中select一个合适的模块; – gzip或zlib,具体取决于您的具体需求。
如果你想产生一个完整的gzip
兼容二进制string, gzip.GzipFile
,你可以使用gzip.GzipFile
与StringIO
一起:
import StringIO import gzip out = StringIO.StringIO() with gzip.GzipFile(fileobj=out, mode="w") as f: f.write("This is mike number one, isn't this a lot of fun?") out.getvalue() # returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff\x0b\xc9\xc8,V\x00\xa2\xdc\xcc\xecT\x85\xbc\xd2\xdc\xa4\xd4"\x85\xfc\xbcT\x1d\xa0X\x9ez\x89B\tH:Q!\'\xbfD!?M!\xad4\xcf\x1e\x00w\xd4\xea\xf41\x00\x00\x00'
最简单的方法是zlib
编码 :
compressed_value = s.encode("zlib")
然后你解压缩它:
plain_string_again = compressed_value.decode("zlib")
s = "a long string of characters" g = gzip.open('gzipfilename.gz', 'w', 5) # ('filename', 'read/write mode', compression level) g.write(s) g.close()