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

相关文章

Python通过PIL获取图片主要颜色并和颜色库进行对比的方法

本文实例讲述了Python通过PIL获取图片主要颜色并和颜色库进行对比的方法。分享给大家供大家参考。具体分析如下: 这段代码主要用来从图片提取其主要颜色,类似Goolge和Baidu的图...

利用Python-iGraph如何绘制贴吧/微博的好友关系图详解

利用Python-iGraph如何绘制贴吧/微博的好友关系图详解

前言 最近工作中遇到了一些需求,想通过图形化的方式显示社交网络特定用户的好友关系,上网找了一下这方面的图形库有networkx、graphviz等,找了好久我选择了iGraph这个图形库...

Python语法快速入门指南

Python语法快速入门指南

Python语言与Perl,C和Java等语言有许多相似之处。但是,也存在一些差异。 在本章中我们将来学习Python的基础语法,让你快速学会Python编程。 第一个Python程序...

python 发送和接收ActiveMQ消息的实例

ActiveMQ是java开发的消息中间件服务。可以支持多种协议(AMQP,MQTT,OpenWire,Stomp),默认的是OpenWire。而python与ActiveMQ的通信使用...

Python时间序列处理之ARIMA模型的使用讲解

Python时间序列处理之ARIMA模型的使用讲解

ARIMA模型 ARIMA模型的全称是自回归移动平均模型,是用来预测时间序列的一种常用的统计模型,一般记作ARIMA(p,d,q)。 ARIMA的适应情况 ARIMA模型相对来说比较简单...