python通过zlib实现压缩与解压字符串的方法

yipeiwu_com6年前Python基础

本文实例讲述了python通过zlib实现压缩与解压字符串的方法。分享给大家供大家参考。具体实现方法如下:

使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。如下

复制代码 代码如下:
#coding=utf-8
import zlib
s = "hello word, 00000000000000000000000000000000"
print len(s)
c = zlib.compress(s)
print len(c)
d =  zlib.decompress(c)
print d

 
示范代码2:
复制代码 代码如下:
import zlib
message = 'witch which has which witches wrist watch'
compressed = zlib.compress(message)
decompressed = zlib.decompress(compressed)
print 'original:', repr(message)
print 'compressed:', repr(compressed)
print 'decompressed:', repr(decompressed) #输出original: 'witch which has which witches wrist watch'
compressed: 'xx9c+xcf,IxceP(xcfxc8x04x92x19x89xc5PV9H4x15xc8+xca,.Q(Ox04xf2x00D?x0fx89'
decompressed: 'witch which has which witches wrist watch'

如果我们要对字符串进行解压可以使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压
复制代码 代码如下:
def compress(infile, dst, level=9):
    infile = open(infile, 'rb')
    dst = open(dst, 'wb')
    compress = zlib.compressobj(level)
    data = infile.read(1024)
    while data:
        dst.write(compress.compress(data))
        data = infile.read(1024)
    dst.write(compress.flush())
def decompress(infile, dst):
    infile = open(infile, 'rb')
    dst = open(dst, 'wb')
    decompress = zlib.decompressobj()
    data = infile.read(1024)
    while data:
        dst.write(decompress.decompress(data))
        data = infile.read(1024)
    dst.write(decompress.flush())

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python cookbook(数据结构与算法)从字典中提取子集的方法示例

本文实例讲述了Python从字典中提取子集的方法。分享给大家供大家参考,具体如下: 问题:想创建一个字典,其本身是另一个字典的子集 解决方案:利用字典推导式(dictionary com...

Python打印输出数组中全部元素

学习Python的人都知道数组是最常用的的数据类型,为了保证程序的正确性,需要调试程序。 因此,需要在程序中控制台中打印数组的全部元素,如果数组的容量较小,例如 只含有10个元素,采用p...

Python输出PowerPoint(ppt)文件中全部文字信息的方法

本文实例讲述了Python输出PowerPoint(ppt)文件中全部文字信息的方法。分享给大家供大家参考。具体分析如下: 下面的代码依赖于windows com,所以必须在机器上安装P...

浅谈python中截取字符函数strip,lstrip,rstrip

浅谈python中截取字符函数strip,lstrip,rstrip

一、起因 今天在做角色控制中,有一个地方用到rstrip,判断用户请求的url是否与数据库对应可用权限中url相符。 if request.path == x.url or reques...

Python+matplotlib+numpy绘制精美的条形统计图

Python+matplotlib+numpy绘制精美的条形统计图

本文实例主要向大家分享了一个Python+matplotlib+numpy绘制精美的条形统计图的代码,效果展示如下: 完整代码如下: import matplotlib.pyplo...