zlib TypeError:需要一个类似字节的对象,而不是“str" [英] zlib TypeError: a bytes-like object is required, not 'str'

查看:28
本文介绍了zlib TypeError:需要一个类似字节的对象,而不是“str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码对文本进行编码和压缩.但它不能正常工作:

回溯(最近一次调用最后一次):文件E:\SOUND.py",第 114 行,在  中unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))类型错误:需要类似字节的对象,而不是str"

你能帮我吗?

导入 zlib,gzipdef str2hex(s):返回 binascii.hexlify(bytes(str.encode(s)))def hex2str(h):返回 binascii.unhexlify(h)十六进制字符串 = 输入()如果 len(hexstring) >200:hexstring = str(zlib.compress(hexstring.encode('utf-8')))打印(十六进制字符串)hexstring = str2hex(hexstring)ph = str(hexstring.decode('utf-8'))打印(ph)#解压文本unhexsring = hex2str(hexstring).decode('utf8')如果 str(unhexsring) 中的x":打印('压缩')unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))打印(unhexsring)

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

所以编码效果很好.

我的问题是当我得到编码字符串并压缩它时,我无法解压缩它.它应该如何工作:

1>s = input('some text')2>如果镜头>200: s = str(zlib.compress(s.encode('utf-8')))3> 使用 str2hex() 对其进行编码4> 用 hex2str() 解码5>str(zlib.decompress(unhexs).encode('utf8')) <--------- 这里

而且我无法正确解压缩它,因为得到了这个:

下一个控制台转储

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 位 (Intel)] on win32输入copyright"、credits"或license()"以获取更多信息.>>>======================== 重新启动:E:\SOUND.py ========================dghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghb'x\x9c\xed\x8d\xb1\r\xc0@\x08\x03\x97\xb5\xb0e\x7f\x87\xb2\x7f\x9eO\x93\x05\xd2\xa5\x02\x1d>\x0cj\x05W\xab\x18\xa3K\\\xb1\x1aE\x0b\x9d\xb2\x98\x83\xf7\xf5dz\x86\xb3#q\x8d<\x84\x8fc\n\xe9Q7^0C\x13\x15\xcc\xfe7~\xd0x\x03\x88\x05\xbb\x9d'6227785c7839635c7865645c7838645c7862315c725c786330405c7830385c7830335c7839375c7862355c786230655c7837665c7838375c7862325c7837665c7839654f5c7839335c7830355c7864325c7861355c7830325c7831643e5c7830636a5c783035575c7861625c7831385c7861334b5c5c5c7862315c783161455c7830625c7839645c7862325c7839385c7838335c7866375c786635647a5c7838365c78623323715c7838643c5c7838345c783866635c6e5c786539515e30435c7865375c7831335c7831355c7863635c786665377e5c786430785c7830335c7838385c7830355c7862625c78396427压缩的回溯(最近一次调用最后一次): 中的文件E:\SOUND.py",第 114 行unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))类型错误:需要类似字节的对象,而不是str"

解决方案

您在此处看到的异常:

unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))类型错误:需要类似字节的对象,而不是str"

被引发是因为 zlib.decompress 需要 bytes.这很容易通过更改来解决

unhexsring = hex2str(hexstring).decode('utf8') # ->字符串

unhexsring = hex2str(hexstring) # ->字节

然而这会导致一个新的错误:

unhexsring = zlib.decompress(unhexsring)zlib.error: 解压数据时出错 -3: 不正确的标头检查

这是因为这一行:

hexstring = str(zlib.compress(hexstring.encode('utf-8')))

bytes 实例上调用 str 不会将 bytes 转换为 str,它会转换字节' reprstr.

<预><代码>>>>bs = 'Hello World'.encode('utf-8')>>>打印(repr(bs))b'你好世界'>>>s = str(bs)>>>打印(代表)b'Hello World'"# <- 注意 b....

str 转换在压缩数据的前面插入了一个b",因此破坏了标头.现在让我们将 hexstring 作为字节对象保留

hexstring = zlib.compress(hexstring.encode('utf-8'))

但现在代码引发了另一个异常:

return binascii.hexlify(bytes(str.encode(s)))类型错误:描述符编码"需要str"对象,但收到字节"

s 现在是一个 bytes 对象,因此无需尝试转换它(并注意 str.encode 返回 bytes 无论如何,所以即使 s 是一个字符串,bytes 调用也是多余的.

所以 str2hex 变成了

def str2hex(s):返回 binascii.hexlify(s)

现在又出现了另一个错误:

unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))AttributeError: 'bytes' 对象没有属性 'encode'

zlib.decompress 的输出是一个 bytes 对象,所以它已经被编码(假设它是一个字符串开头).您想对其进行解码以获得 str:

unhexsring = zlib.decompress(unhexsring).decode('utf8')

这是可以从命令提示符作为脚本运行的代码版本:

import binascii随机导入导入字符串导入 zlibdef str2hex(s):返回 binascii.hexlify(s)def hex2str(h):返回 binascii.unhexlify(h)定义主():# 我不想输入 200 多个字符来测试这个 :-)hexstring = ''.join(random.choices(string.ascii_letters, k=201))hexstring = hexstring.encode('utf-8')如果 len(hexstring) >200:hexstring = zlib.compress(hexstring)打印(十六进制字符串)hexstring = str2hex(hexstring)ph = hexstring.decode('utf-8')打印(ph)# 解压文本unhexsring = hex2str(hexstring)# 检查字符串中的 'x' 不是检查的好方法# 压缩.首先尝试解码,如果失败,我们知道我们有# 压缩文本.尝试:unhexsring = unhexsring.decode('utf-8')除了 UnicodeDecodeError:打印('压缩')unhexsring = zlib.decompress(unhexsring).decode('utf8')打印(unhexsring)如果 __name__ == '__main__':主要的()

I use this code to encode and compress text. But it doesn't work properly:

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' 

Can you help me?

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)

This code will not decompress the zlib-compressed text.

So encoding work good.

My trouble is when I get encoded string and compress it I can't decompress it. How should it works:

1>s = input('some text')
2>if len(s) > 200: s = str(zlib.compress(s.encode('utf-8'))) 
3>encoding it with str2hex()
4>decode it with hex2str()
5>str(zlib.decompress(unhexs).encode('utf8'))  <---------- HERE

And I can't decompress it properly because getting this:

CONSOLE DUMP NEXT

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
========================= RESTART: E:\SOUND.py =========================
dghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjghdghlkdushfgkjdsfhglkjhsdfgjhdskfjhgkdsfhgkjdhfgkjsdhfgjkhsdkjfghlkjsdhgkjhsdfjghdksjhgkjsdhgkjhsdfkjghdskfjghkdjgh
b'x\x9c\xed\x8d\xb1\r\xc0@\x08\x03\x97\xb5\xb0e\x7f\x87\xb2\x7f\x9eO\x93\x05\xd2\xa5\x02\x1d>\x0cj\x05W\xab\x18\xa3K\\\xb1\x1aE\x0b\x9d\xb2\x98\x83\xf7\xf5dz\x86\xb3#q\x8d<\x84\x8fc\n\xe9Q^0C\xe7\x13\x15\xcc\xfe7~\xd0x\x03\x88\x05\xbb\x9d'
6227785c7839635c7865645c7838645c7862315c725c786330405c7830385c7830335c7839375c7862355c786230655c7837665c7838375c7862325c7837665c7839654f5c7839335c7830355c7864325c7861355c7830325c7831643e5c7830636a5c783035575c7861625c7831385c7861334b5c5c5c7862315c783161455c7830625c7839645c7862325c7839385c7838335c7866375c786635647a5c7838365c78623323715c7838643c5c7838345c783866635c6e5c786539515e30435c7865375c7831335c7831355c7863635c786665377e5c786430785c7830335c7838385c7830355c7862625c78396427
compressed
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'

解决方案

The exception you see here:

unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
    TypeError: a bytes-like object is required, not 'str'

is raised because zlib.decompress expects bytes. This is easily fixed by changing

unhexsring = hex2str(hexstring).decode('utf8')    # -> str

to

unhexsring = hex2str(hexstring)    # -> bytes

However this results in a new error:

unhexsring = zlib.decompress(unhexsring)
    zlib.error: Error -3 while decompressing data: incorrect header check

This one is happening because of this line:

hexstring = str(zlib.compress(hexstring.encode('utf-8')))

Calling str on a bytes instance doesn't convert the bytes to str, it converts the bytes' repr to str.

>>> bs = 'Hello World'.encode('utf-8')
>>> print(repr(bs))
b'Hello World'
>>> s = str(bs)
>>> print(repr(s))
"b'Hello World'"    # <- note the b....

The str conversion is inserting a 'b' at the front of the compressed data and so corrupting the header. Let's leave hexstring as a bytes object for now

hexstring = zlib.compress(hexstring.encode('utf-8'))

But now the code raises yet another exception:

return binascii.hexlify(bytes(str.encode(s)))
    TypeError: descriptor 'encode' requires a 'str' object but received a 'bytes'

s is now a bytes object, so there's no need try to convert it (and note that str.encode returns bytes anyway, so the bytes call would be redundant even if s were a string).

So str2hex becomes

def str2hex(s):
    return binascii.hexlify(s)

Now yet another error is raised:

unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
    AttributeError: 'bytes' object has no attribute 'encode'

The output of zlib.decompress is a bytes object, so it's already encoded (assuming it was a string to begin with). You want to decode it to get a str:

unhexsring = zlib.decompress(unhexsring).decode('utf8')

This is a version of your code that can be run as a script from the command prompt:

import binascii
import random
import string
import zlib

def str2hex(s):
    return binascii.hexlify(s)

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

def main():
    # I don't want to type 200+ chars to test this :-)
    hexstring = ''.join(random.choices(string.ascii_letters, k=201))
    hexstring = hexstring.encode('utf-8')
    if len(hexstring) > 200:
        hexstring = zlib.compress(hexstring)
    print(hexstring)
    hexstring = str2hex(hexstring)
    ph = hexstring.decode('utf-8')
    print(ph)

    # decompressing text
    unhexsring = hex2str(hexstring)
    # Checking for 'x' in the string isn't a good way to check for 
    # compression. Try decoding first and if that fails we know we have 
    # compressed text. 
    try:
        unhexsring = unhexsring.decode('utf-8')
    except UnicodeDecodeError:
        print('compressed')
        unhexsring = zlib.decompress(unhexsring).decode('utf8')
    print(unhexsring)

if __name__ == '__main__':
    main()

这篇关于zlib TypeError:需要一个类似字节的对象,而不是“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆