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通过scapy获取局域网所有主机mac地址示例

python通过scapy获取局域网所有主机mac地址示例

python通过scapy获取局域网所有主机mac地址复制代码 代码如下:#!/usr/bin/env python# -*- coding: utf-8 -*-from scapy.a...

Python简单计算数组元素平均值的方法示例

Python简单计算数组元素平均值的方法示例

本文实例讲述了Python简单计算数组元素平均值的方法。分享给大家供大家参考,具体如下: Python 环境:Python 2.7.12 x64 IDE :  &nb...

详解Python3的TFTP文件传输

详解Python3的TFTP文件传输

TFTP文件传输 功能: 1、获取文件列表 2、上传文件 3、下载文件 4、退出 第一部分,TftpServer部分。 ①导入相关模块 from socket import * im...

Python数据库的连接实现方法与注意事项

在Python中要连接数据库,首先我们得先安装几个重要的东西,主要有:  (1)Python-dev包  (2)setuptools-0.6c11.tar.gz &n...

关于 Python opencv 使用中的 ValueError: too many values to unpack

最近在OpenCV-Python接口中使用cv2.findContours()函数来查找检测物体的轮廓。 根据网上的 教程,Python OpenCV的轮廓提取函数会返回两个值...