以下是我找到的具体答案以及示例代码。
1.我们可以从预设的单词中生成和使用自定义的 deflate 字典吗?
是的,这是可以做到的。 python中的一个简单示例如下:
import zlib
#Data for compression
hello = b'hello'
#Compress with dictionary
co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
compress_data = co.compress(hello) + co.flush()
2。我们可以在没有 deflate 字典的情况下发送文件并使用本地字典吗?
是的,您可以只发送不带字典的数据。压缩数据在上述示例代码中的compress_data 中。但是,要解压缩,您需要在压缩过程中传递 zdict 值。解压方式示例:
hello = b'hello' #for passing to zdict
do = zlib.decompressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
data = do.decompress(compress_data)
包含和不包含 dict 数据的完整示例代码:
import zlib
#Data for compression
hello = b'hello'
#Compression with dictionary
co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
compress_data = co.compress(hello) + co.flush()
#Compression without dictionary
co_nodict = zlib.compressobj(wbits=-zlib.MAX_WBITS, )
compress_data_nodict = co_nodict.compress(hello) + co_nodict.flush()
#De-compression with dictionary
do = zlib.decompressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
data = do.decompress(compress_data)
#print compressed output when dict used
print(compress_data)
#print compressed output when dict not used
print(compress_data_nodict)
#print decompressed output when dict used
print(data)
以上代码不适用于 unicode 数据。对于 unicode 数据,您必须执行以下操作:
import zlib
#Data for compression
unicode_data = 'റെക്കോർഡ്'
hello = unicode_data.encode('utf-16be')
#Compression with dictionary
co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
compress_data = co.compress(hello) + co.flush()
...
基于 JS 的方法参考:
- How to find a good/optimal dictionary for zlib 'setDictionary' when processing a given set of data?
- Compression of data with dictionary using zlib in node.js