python通過(guò)zlib實(shí)現(xiàn)壓縮與解壓字符串的方法
本文實(shí)例講述了python通過(guò)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ì)有所幫助。
相關(guān)文章
python報(bào)錯(cuò)unexpected?indent的解決辦法
這篇文章主要給大家介紹了關(guān)于python報(bào)錯(cuò)unexpected?indent的解決辦法,在python中出現(xiàn)"Unexpected indent"可能是代碼的縮進(jìn)出現(xiàn)問(wèn)題,需要的朋友可以參考下2023-06-06
pycharm 使用心得(八)如何調(diào)用另一文件中的函數(shù)
事件環(huán)境: pycharm 編寫了函數(shù)do() 保存在make.py 如何在另一個(gè)file里調(diào)用do函數(shù)?2014-06-06
Python全局變量與global關(guān)鍵字常見(jiàn)錯(cuò)誤解決方案
這篇文章主要介紹了Python全局變量與global關(guān)鍵字常見(jiàn)錯(cuò)誤解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
PyTorch如何使用embedding對(duì)特征向量進(jìn)行嵌入
這篇文章主要介紹了PyTorch如何使用embedding對(duì)特征向量進(jìn)行嵌入問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Python語(yǔ)法之精妙的十個(gè)知識(shí)點(diǎn)(裝B語(yǔ)法)
本文精心篩選了最能展現(xiàn) Python 語(yǔ)法之精妙的十個(gè)知識(shí)點(diǎn),并附上詳細(xì)的實(shí)例代碼,需要的朋友可以參考下2020-01-01
Pytorch使用DataLoader實(shí)現(xiàn)批量加載數(shù)據(jù)
這篇文章主要介紹了Pytorch使用DataLoader實(shí)現(xiàn)批量加載數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
PyCharm更換pip源、模塊安裝以及PyCharm依賴包導(dǎo)入導(dǎo)出功能
這篇文章主要給大家介紹了關(guān)于PyCharm更換pip源、模塊安裝以及PyCharm依賴包導(dǎo)入導(dǎo)出功能的相關(guān)資料,我們?cè)谑褂胮ycharm的時(shí)候,pycharm中的虛擬環(huán)境依賴包需要導(dǎo)出成一個(gè)文件,需要的朋友可以參考下2023-11-11

