小场景:需要对传输的字节进行压缩传输
解压缩的一席而基础知识介绍:
压缩字符串和元字符串对比测试:
import zlib
import this
import os
def main():
# python_zen = this.s # 获取Python之禅的Unicode字符串
python_zen ="123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910" # 获取Python之禅的Unicode字符串
com_bytes = zlib.compress(python_zen.encode('utf-8')) # 编码为UTF-8格式的字节进行压缩
print("开始:",com_bytes)
size = len(com_bytes)
print("字节数:",size)
print("原始字节:",len(python_zen.encode()))
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 # 获取字符
python_zen = "123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910123456789101234567891012345678910" # 获取字符
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()