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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

Python3实现的简单验证码识别功能示例

本文实例讲述了Python3实现的简单验证码识别功能。分享给大家供大家参考,具体如下: 这次的需求是自动登录某机构网站, 其验证码很具特色, 很适合做验证码识别入门demo, 先贴主要代...

Python函数式编程指南(二):从函数开始

2. 从函数开始 2.1. 定义一个函数 如下定义了一个求和函数: 复制代码 代码如下: def add(x, y):     return x + y...

对Python 中矩阵或者数组相减的法则详解

对Python 中矩阵或者数组相减的法则详解

最近在做编程练习,发现有些结果的值与答案相差较大,通过分析比较得出结论,大概过程如下: 定义了一个计算损失的函数: def error(yhat,label): yhat = np...

django 解决manage.py migrate无效的问题

问题描述: 已有的model,修改之后,想重新建模,于是将migrations文件夹中除__init__.py之外其他文件都删掉,再次执行以下步骤python manage.py mak...

python3中os.path模块下常用的用法总结【推荐】

abspath 返回一个目录的绝对路径 Return an absolute path. >>> os.path.abspath("/etc/sysconfig/...