Python使用zlib對數據進行簡單壓
- 2020 年 1 月 13 日
- 筆記
Python對數據進行簡單壓縮處理
在Python豐富的庫中,也有著對數據進行壓縮處理的庫(zlib)。對於需要數據壓縮的應用程式,此模組中的功能允許使用zlib庫進行壓縮和解壓縮。 (本文只對簡單的字元串數據進行壓縮,如需壓縮文件等複雜數據類型,詳見zlib官網進行更詳細的學習)
Python3的字元串類型為Unicode,而非位元組。
對Unicode字元串進行壓縮,先得將字元串編碼為位元組形式,通過zlib.compress()方法壓縮位元組數據。
對壓縮後的位元組數據進行解壓縮,通過zlib.decompress()方法解壓縮位元組數據,再將位元組數據解碼為Unicode字元串
在這裡我們將Python之禪進行壓縮和解壓縮處理
import zlib import this def main(): python_zen = this.s # 獲取Python之禪的Unicode字元串 com_bytes = zlib.compress(python_zen.encode('utf-8')) # 編碼為UTF-8格式的位元組進行壓縮 print(com_bytes) decom_bytes = zlib.decompress(com_bytes) # 將壓縮的位元組進行解壓縮 print(decom_bytes.decode('utf-8')) # 將解壓縮的位元組進行UTF-8解碼得到Unicode字元串 if __name__ == '__main__': main()在這裡我們好像看不出什麼效果來,我們將數據存儲在文件中,查看文件大小來區分壓縮和未壓縮。
import this import zlib def main(): python_zen = this.s # 獲取字元 with open('data.txt', 'wb') as f: # 使用文件寫入的上下文環境 f.write(python_zen.encode('utf-8')) # 寫入未壓縮的位元組數據 with open('com_data.txt', 'wb') as f: # 使用文件寫入上下文環境 com_zen = zlib.compress(python_zen.encode('utf-8')) # 將字元串編碼並壓縮 f.write(com_zen) # 寫入壓縮後的位元組數據 if __name__ == '__main__': main()運行程式碼看看壓縮結果吧
[tianjun@192 zlib_example]$ python3 example06.py The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! [tianjun@192 zlib_example]$ ll 總用量 12 -rw-rw-r--. 1 tianjun tianjun 445 6月 4 00:16 com_data.txt -rw-rw-r--. 1 tianjun tianjun 856 6月 4 00:16 data.txt -rw-rw-r--. 1 tianjun tianjun 505 6月 4 00:15 example06.py
可以清楚的看到原數據data.txt大小為856位元組,壓縮後com_data.txt大小為445位元組,由此可見壓縮效果非常的好,壓縮了接近50%。