翼度科技»论坛 编程开发 python 查看内容

Python工具箱系列(三十九)

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
使用zlib对数据进行压缩

现实世界中,大量存在着对数据压缩的需求。为此,python内置了zlib压缩库,可以方便的对任意对象进行压缩。
下述代码演示了对字符串进行压缩:
  1. import zlib
  2. # 压缩一段中文
  3. originstr = '神龟虽寿,犹有竟时;腾蛇乘雾,终为土灰。老骥伏枥,志在千里;烈士暮年,壮心不已。盈缩之期,不但在天;养怡之福,可得永年。幸甚至哉,歌以咏志。'
  4. print(len(originstr))
  5. str_compression = zlib.compress(originstr.encode('utf-8'), level=8)
  6. print(len(str_compression))
  7. print(str_compression)
  8. decompress_str = zlib.decompress(str_compression)
  9. print(decompress_str)
  10. print(decompress_str.decode('utf-8'))
  11. # 压缩一段英文
  12. originstr = 'The World Health Organization officially declared on Saturday that the current multi-country monkeypox outbreak outside of the traditional endemic areas in Africa has already turned into a public health emergency of international concern (PHEIC).'
  13. print(len(originstr))
  14. str_compression = zlib.compress(originstr.encode('utf-8'), level=8)
  15. print(len(str_compression))
  16. print(str_compression)
  17. decompress_str = zlib.decompress(str_compression)
  18. print(decompress_str)
  19. print(decompress_str.decode('utf-8'))
复制代码
运行上述代码后,会发现压缩并不一定会减少字节数,压缩的效率取决于压缩内容中的冗余程度。对于第一句的中文压缩后反而增加了字节数。但第二段英文则有明显的压缩比(246/180)。此外,在压缩时不指定level则使用缺省的压缩级别(大约是6),是一个在速度与压缩比间的平衡值。level的设定如下:


    • level=0,效果是不压缩。
    • level=1,速度最快
    • level=9,速度最慢,压缩比最高
    • level=-1,缺省值
      压缩一个文件的操作类似,示例代码如下:

  1. import zlib
  2. def compress(inputfile,outputfile):
  3.     with open(inputfile,'rb') as input:
  4.         with open(outputfile,'wb') as output:
  5.             data = input.read()
  6.             compressdata = zlib.compress(data)
  7.             output.write(compressdata)
  8. def decompress(inputfile,outputfile):
  9.    with open(inputfile,'rb') as input:
  10.         with open(outputfile,'wb') as output:
  11.             data = input.read()
  12.             compressdata = zlib.decompress(data)
  13.             output.write(compressdata)
  14. compress(r'd:\dev\sensor.dat',r'd:\dev\sensor.zlib')
  15. decompress(r'd:\dev\sensor.zlib',r'd:\dev\sensor_d.dat')
复制代码
使用vscode的hex editor可以打开三个文件如下图所示:

首先源文件与压缩解压后的文件完全一样。其次,压缩后的文件确实小多了。最后可以看出,从某种意义上来说,压缩也相当于加密。
 

来源:https://www.cnblogs.com/shanxihualu/p/17593047.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具