国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python通過zlib實現壓縮與解壓字符串的方法

2020-02-23 06:12:24
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 天津市| 河北省| 郴州市| 两当县| 馆陶县| 甘洛县| 抚松县| 博爱县| 蕉岭县| 龙州县| 郴州市| 正镶白旗| 保定市| 仁寿县| 肇庆市| 喀喇沁旗| 城口县| 浏阳市| 瓦房店市| 拜城县| 封开县| 镇坪县| 射阳县| 天柱县| 芒康县| 长治县| 丹江口市| 泸定县| 白玉县| 蓬安县| 高州市| 申扎县| 赤城县| 遵化市| 岐山县| 铜鼓县| 林州市| 调兵山市| 麻江县| 石家庄市| 玉溪市|