How to compress or compact a string in Python

后端 未结 2 616
暗喜
暗喜 2021-02-08 01:42

I\'m making a python \"script\" that sends a string to a webservice (in C#). I NEED to compress or compact this string, because the bandwidth and MBs data is LIMITED (yeah, in c

相关标签:
2条回答
  • 2021-02-08 01:51
    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)
    

    0 讨论(0)
  • 2021-02-08 01:52

    How about zlib?

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

    You can also use sys.getsizeof(obj) to see how much data an object takes up before and after compression.

    0 讨论(0)
提交回复
热议问题