python gzip+base64方式壓縮

gzip方式下的兩種壓縮:

1. gzip+base64方式壓縮,如果壓縮對象本事比較小,壓縮後因爲base64緣故反而會變大,因此,只有長度很大,要利於傳輸數據才採用該方式;

2. gzip原始方式壓縮。

#!/usr/bin/python3  
# encoding: utf-8  
""" 
@version: v1.0 
@author: W_H_J 
@license: Apache Licence  
@contact: [email protected] 
@software: PyCharm 
@file: gzipAndBase64.py
@time: 2019/7/9 10:09 
@describe: gzip方式壓縮與解壓
"""
import sys
import os
import base64
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
import gzip  # 導入python gzip模塊,注意名字爲全小寫


def gzip_zip_base64(content):
    """
    gzip+base64壓縮
        這種方式在壓縮對象比較短/小的時候效果並不明顯,因爲base64之後反而會變大,但是壓縮對象比較大時纔有效果
    :param content:
    :return:
    """
    bytes_com = gzip.compress(str(content).encode("utf-8"))
    base64_data = base64.b64encode(bytes_com)
    back = str(base64_data.decode())
    return back, sys.getsizeof(back)
    # 對gzip文件的讀寫操作
    # with gzip.open('./log/zip-test.gz', 'wb') as write:
    #     write.write(str(back).encode("utf-8"))


def gzip_unzip_base64(content):
    """
    base64+gzip解壓
    :param content:
    :return:
    """
    base64_data = base64.b64decode(content)
    bytes_decom = gzip.decompress(base64_data)
    str_unzip = bytes_decom.decode()
    return str_unzip, sys.getsizeof(str_unzip)


def gzip_zip(content):
    """
    gzip方式壓縮數據
    :param content: 要壓縮對象
    :return: [0, 1]: 0:壓縮對象;1:壓縮後大小
    """
    bytes_com = gzip.compress(str(content).encode("utf-8"))
    return bytes_com, sys.getsizeof(bytes_com)
    # print(bytes_com)
    # with gzip.open('./lognew/zip-base-test.gz', 'wb') as write:
    #     write.write(str(content).encode("utf-8"))


def gzip_unzip(content):
    """
    gzip unzip 方式解壓數據
    :param content: 要解壓對象
    :return:
    """
    bytes_decom = gzip.decompress(content).decode()
    return bytes_decom, sys.getsizeof(bytes_decom)


if __name__ == '__main__':
    str_test = "python 實現gzip壓縮並base編碼"
    # sys.getsizeof()  # 返回該對象的在內存中所佔字節大小
    
    # 原始方式壓縮結果
    long_str = len(str_test)
    size_str = sys.getsizeof(str_test)
    gzip_str = gzip_zip(str_test)
    gunzip_str = gzip_unzip(gzip_str[0])
    print("原始字符串:{0}; \n壓縮後字符串:{1};\n解壓後對象:{2};".format(str_test, gzip_str[0], gunzip_str[0]))
    print("原始字符串長度:{0};\n原始字符串佔內存字節大小:{1};\n壓縮後佔內存字節大小:{2};\n解壓後佔內存大小:{3}".format(long_str, size_str, gzip_str[1], gunzip_str[1]))

結果:

原始字符串:python 實現gzip壓縮並base編碼; 
壓縮後字符串:b'\x1f\x8b\x08\x00\xe6\xbe6]\x02\xff\x01$\x00\xdb\xffpython \xe5\xae\x9e\xe7\x8e\xb0gzip\xe5\x8e\x8b\xe7\xbc\xa9\xe5\xb9\xb6base\xe7\xbc\x96\xe7\xa0\x815\x83@\xc2$\x00\x00\x00';
解壓後對象:python 實現gzip壓縮並base編碼;
原始字符串長度:22;
原始字符串佔內存字節大小:118;
壓縮後佔內存字節大小:92;
解壓後佔內存大小:118

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章