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中常用的九种预处理方法分享

python中常用的九种预处理方法分享

本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean R...

Django处理多用户类型的方法介绍

Django处理多用户类型的方法介绍

起步 这是许多开发者在项目初期要面临的一个普遍问题。要怎样来处理多用户类型。 本文讲介绍对于不同场景和业务需求如何设计用户模型。为项目提供指导设计。 设计之前 在梳理用户设计之前,有...

Python中用Spark模块的使用教程

 在日常的编程中,我经常需要标识存在于文本文档中的部件和结构,这些文档包括:日志文件、配置文件、定界的数据以及格式更自由的(但还是半结构化的)报表格式。所有这些文档都拥有它们自...

python实现事件驱动

本文实例为大家分享了python实现事件驱动的具体代码,供大家参考,具体内容如下 EventManager事件管理类实现,大概就百来行代码左右。 # encoding: UTF-8...

Python中在脚本中引用其他文件函数的实现方法

在导入文件的时候,Python只搜索当前脚本所在的目录,加载(entry-point)入口脚本运行目录和sys.path中包含的路径例如包的安装地址。所以如果要在当前脚本引用其他文件,除...