如何在Python中压缩或压缩字符串

San*_*rez 2 python compression string stream-compaction

我正在制作一个python"脚本",它将一个字符串发送到一个web服务(在C#中).我需要压缩或压缩这个字符串,因为带宽和MB数据是有限的(是的,在大写字母,因为它非常有限).

我在考虑将其转换为文件,然后压缩文件.但我正在寻找一种直接压缩字符串的方法.

如何压缩或压缩字符串?

hmi*_*mir 8

zlib怎么样?

import zlib

a = "this string needs compressing"
a = zlib.compress(a)
print zlib.decompress(a) #outputs original contents of a
Run Code Online (Sandbox Code Playgroud)

您还可以使用sys.getsizeof(obj)查看对象在压缩之前和之后占用的数据量.

  • 在Python 3中,`zlib.compress()`采用类似字节的值,因此您需要执行`zlib.compress(a.encode())`之类的操作。 (2认同)

SAT*_*ANG 5

import sys
import zlib


text=b"""This function is the primary interface to this module along with 
decompress() function. This function returns byte object by compressing the data 
given to it as parameter. The function has another parameter called level which 
controls the extent of compression. It an integer between 0 to 9. Lowest value 0 
stands for no compression and 9 stands for best compression. Higher the level of 
compression, greater the length of compressed byte object."""

# Checking size of text
text_size=sys.getsizeof(text)
print("\nsize of original text",text_size)

# Compressing text
compressed = zlib.compress(text)

# Checking size of text after compression
csize=sys.getsizeof(compressed)
print("\nsize of compressed text",csize)

# Decompressing text
decompressed=zlib.decompress(compressed)

#Checking size of text after decompression
dsize=sys.getsizeof(decompressed)
print("\nsize of decompressed text",dsize)

print("\nDifference of size= ", text_size-csize)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明