小编Вла*_*ков的帖子

zlib TypeError:需要一个类似字节的对象,而不是'str'

我使用此代码来编码和压缩文本。但是它不能正常工作:

Traceback (most recent call last): File "E:\SOUND.py", line 114, in <module>
unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
TypeError: a bytes-like object is required, not 'str' 
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗?

import zlib,gzip

def str2hex(s):
    return binascii.hexlify(bytes(str.encode(s)))


def hex2str(h):
    return binascii.unhexlify(h)

hexstring = input()
if len(hexstring) > 200:
    hexstring = str(zlib.compress(hexstring.encode('utf-8')))
    print(hexstring)
hexstring = str2hex(hexstring)
ph = str(hexstring.decode('utf-8'))
print(ph)

#decompressing text
unhexsring = hex2str(hexstring).decode('utf8')
if 'x' in str(unhexsring):
    print('compressed')
    unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
print(unhexsring)
Run Code Online (Sandbox Code Playgroud)

此代码不会解压缩zlib压缩的文本。

因此编码工作良好。

我的麻烦是当我获取编码的字符串并对其进行压缩时,我无法对其进行解压缩。应该如何运作:

1>s = input('some text')
2>if len(s) > 200: s = str(zlib.compress(s.encode('utf-8'))) …
Run Code Online (Sandbox Code Playgroud)

python zlib python-3.x

1
推荐指数
1
解决办法
2909
查看次数

标签 统计

python ×1

python-3.x ×1

zlib ×1