python通過zlib實(shí)現(xiàn)壓縮與解壓字符串的方法
本文實(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'
如果我們要對字符串進(jìn)行解壓可以使用zlib.compressobj和zlib.decompressobj對文件進(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())
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python中TypeError:unhashable?type:'dict'錯(cuò)誤的解決辦法
這篇文章主要給大家介紹了關(guān)于Python中TypeError:unhashable?type:'dict'錯(cuò)誤的解決辦法,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-04-04python中format函數(shù)與round函數(shù)的區(qū)別
大家好,本篇文章主要講的是python中format函數(shù)與round函數(shù)的區(qū)別,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01python3實(shí)現(xiàn)用turtle模塊畫一棵隨機(jī)櫻花樹
今天小編就為大家分享一篇python3實(shí)現(xiàn)用turtle模塊畫一棵隨機(jī)櫻花樹,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11python 數(shù)據(jù)庫查詢返回list或tuple實(shí)例
這篇文章主要介紹了python 數(shù)據(jù)庫查詢返回list或tuple實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python發(fā)送郵件封裝實(shí)現(xiàn)過程詳解
這篇文章主要介紹了Python發(fā)送郵件封裝實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05將TensorFlow的模型網(wǎng)絡(luò)導(dǎo)出為單個(gè)文件的方法
本篇文章主要介紹了將TensorFlow的網(wǎng)絡(luò)導(dǎo)出為單個(gè)文件的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04django實(shí)現(xiàn)悲觀鎖樂觀鎖的項(xiàng)目實(shí)踐
在Django中,我們可以通過實(shí)現(xiàn)悲觀鎖和樂觀鎖來保證數(shù)據(jù)的安全性,本文就來介紹一下django實(shí)現(xiàn)悲觀鎖樂觀鎖的項(xiàng)目實(shí)踐,感興趣的可以了解一下2023-08-08