解压缩时Python zlib模块出错?

2024-06-16 10:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

几天前,我编写了一个python程序来压缩一些Html数据并插入到数据库中。我用zlib压缩了它们。你知道吗

html = "<html><head><title>Title</title></head><body><p>Paragraph</p></body></html>"
compressed_html = str(zlib.compress(html.encode('utf-8'))).replace('b\'', '').replace('\'', '')

那么压缩的html变量是这样的

x\\x9c\\xd4\\xbd\\xfbv\\xdb\\xb6\\xb30\\xfa\\x7f\\xd6\\xfa\\xde...

今天我试着这样解压。你知道吗

html = html.encode('utf-8')
# html is retireved from database.
# html is like now b'x\\x9c\\xd4\\xbd\\xfbv\\xdb\\xb6\\xb30\\xfa\\x7f\\xd6\\xfa\\xde...'
decompressed = zlib.decompress(html)

返回一个错误

Traceback (most recent call last):

  File "C:/Users/Sakith Karunasena/PycharmProjects/Twibot Repairer/main.py", 

line 16, in <module>

    decompressed = zlib.decompress(html)

zlib.error: Error -3 while decompressing data: incorrect header check

Tags: titlehtmlbodyheadreplaceutfencodexbd
1条回答
网友
1楼 · 发布于 2024-06-16 10:28:18

要压缩它,用这个

compressed_html = zlib.compress(html.encode(), level=6)

根据所需的压缩比here,级别可以在-1到9之间

要存储它:

with open('filename.txt','wb') as outfile:
    outfile.write(compressed_html)

去读吧

with open('filename.txt','rb') as infile:
    compressed_html = infile.read()

减压回来

decompressed_html = zlib.decompress(compressed_html).decode()

相关问题 更多 >