You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中解压缩lz-string压缩的字符串?

问题:lz-string压缩的内容无法用Python的lzip库解压缩

场景还原

用JavaScript的lz-string工具压缩字符串,代码如下:

JavaScript压缩与解压缩代码

compress.js

var compressed = LZString.compress('abc');

在JavaScript中可正常解压缩:

console.log(LZString.decompress(compressed));

将压缩后的字符串ↂテ䀀复制到剪贴板,尝试用Python的lzip库解压缩,代码如下:

Python尝试解压缩代码(decompress.py)

import lzip

# compressed是从JavaScript复制的剪贴板内容
compressed = 'ↂテ䀀'

compressed_bytes = str.encode(compressed)
print(compressed_bytes)
print(lzip.decompress)

运行后触发错误:

RuntimeError: Lzip error: Header error

问题根源:两种工具的压缩实现完全不兼容

通过对比测试可以明确这一点,测试代码如下:

import lzip

compressed = 'ↂテ䀀'

python_compressed = lzip.compress_to_buffer(str.encode('abc'))
print(f'{python_compressed=}')

compressed_bytes = str.encode(compressed)
print(f'{compressed_bytes=}')

输出结果:

python_compressed=b"LZIP\x01\x17\x000\x98\x88\xa4J\x8e\x9f\xff\xf6c\x80\x00\xc2A$5\x03\x00\x00\x00\x00\x00\x00\x00'\x00\x00\x00\x00\x00\x00\x00"

compressed_bytes=b'\xe2\x86\x82\xe3\x83\x86\xe4\x80\x80'

可见两者的压缩结果格式完全不同:

  • lzip是基于LZMA算法的标准压缩格式,会生成带特定头部标识(LZIP)的二进制数据
  • lz-string是针对JavaScript环境优化的字符串压缩算法,输出的是经过编码的Unicode字符串,并非标准lzip格式

结论

这种跨语言解压缩的方法完全不正确,无法通过Python的lzip库解压lz-string生成的内容。若要在Python中处理lz-string的压缩结果,需要使用Python版本的lz-string实现(而非lzip库)。

内容的提问来源于stack exchange,提问作者Psionman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:10:02