本文實(shí)例講述了python通過zlib實(shí)現(xiàn)壓縮與解壓字符串的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
使用zlib.compress可以壓縮字符串。使用zlib.decompress可以解壓字符串。如下
import zlib
s = "hello word, 00000000000000000000000000000000"
print len(s)
c = zlib.compress(s)
print len(c)
d =? zlib.decompress(c)
print d
?
示范代碼2:
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'
如果我們要對(duì)字符串進(jìn)行解壓可以使用zlib.compressobj和zlib.decompressobj對(duì)文件進(jìn)行壓縮解壓
??? 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())
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
