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

如何在Python中压缩或压缩字符串,python,string,compression,stream-compaction,Python,String,Compression,Stream Compaction,我正在制作一个python“脚本”,将字符串发送到Web服务(用C#)。我需要压缩或压缩这个字符串,因为带宽和MBs数据是有限的(是的,大写,因为它非常有限) 我想把它转换成一个文件,然后压缩文件。但是我正在寻找一种直接压缩字符串的方法 如何压缩或压缩字符串?如何 您还可以使用sys.getsizeof(obj)查看对象在压缩前后占用的数据量 import sys import zlib text=b"""This function is the primary interface to t

我正在制作一个python“脚本”,将字符串发送到Web服务(用C#)。我需要压缩或压缩这个字符串,因为带宽和MBs数据是有限的(是的,大写,因为它非常有限)

我想把它转换成一个文件,然后压缩文件。但是我正在寻找一种直接压缩字符串的方法

如何压缩或压缩字符串?

如何

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

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)

您的web服务会理解您的压缩字符串吗?@Selcuk这就是想法。我的Web服务将解压缩字符串并将其存储在数据库中。如果是重要的,web服务在C#(.NET)中,那么zlib在其他语言中可用吗?我的web服务是C#(很抱歉没有添加这些信息)。我在Python3中发现
zlib.compress()
采用类似字节的值,因此需要执行类似
zlib.compress(a.encode())
的操作才能工作。在Python3中,如果将
text
更改为字符串,
compressed=zlib.compress(text)
应该是
compressed=zlib.compress(text.encode())
。这似乎对于较长的字符串最有效。我用43个长的
[a-v]
字符串进行了尝试,大小差异(SD)只有10。使用
brotlipy
,SD为23。
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)