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

首頁 > 編程 > Python > 正文

python通過zlib實現(xiàn)壓縮與解壓字符串的方法

2019-11-25 18:05:30
字體:
來源:轉載
供稿:網(wǎng)友

本文實例講述了python通過zlib實現(xiàn)壓縮與解壓字符串的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

使用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程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 高阳县| 奎屯市| 怀安县| 嘉禾县| 同心县| 修武县| 新和县| 昆明市| 怀宁县| 连平县| 华坪县| 仁布县| 雅安市| 土默特右旗| 禹城市| 武平县| 扶沟县| 芮城县| 尚志市| 和田市| 织金县| 阜宁县| 芒康县| 吉安市| 齐齐哈尔市| 石棉县| 城口县| 迭部县| 葫芦岛市| 中方县| 独山县| 中牟县| 荣成市| 临澧县| 河南省| 宜宾县| 湘潭市| 图木舒克市| 县级市| 健康| 章丘市|