【问题标题】:How to compress or compact a string in Python如何在 Python 中压缩或压缩字符串
【发布时间】:2015-05-28 09:11:55
【问题描述】:

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

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

如何压缩或压缩字符串?

【问题讨论】:

  • 你的网络服务能理解你的压缩字符串吗?
  • @Selcuk 就是这样。我的网络服务将解压缩字符串并将其存储在数据库中。如果很重要,则 Web 服务使用 C# (.NET)

标签: python string compression stream-compaction


【解决方案1】:

zlib怎么样?

import zlib

a = "this string needs compressing"
a = zlib.compress(a)
print zlib.decompress(a.encode()) #outputs original contents of a

您还可以使用sys.getsizeof(obj) 来查看一个对象在压缩前后占用了多少数据。

【讨论】:

  • 其他语言中是否有可用的 zlib?我的 Web 服务使用 C#(抱歉没有添加该信息)。
  • 我找到了this
  • 在 Python 3 中 zlib.compress() 采用类似字节的值,因此您需要执行类似 zlib.compress(a.encode()) 的操作才能使其工作。
【解决方案2】:
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)

【讨论】:

  • 在 Python 3 中,如果您将text 更改为字符串,则compressed = zlib.compress(text) 应为compressed = zlib.compress(text.encode())。似乎这对于较长的字符串最有效。我用一个 43 长的[a-v] 字符串尝试了这个,大小差异(SD)只有 10。使用brotlipy,SD 是 23。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
相关资源
最近更新 更多