<p>你在这里看到的例外情况是:</p>
<pre><code>unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>引发,因为<code>zlib.decompress</code>需要{<cd2>}。这很容易通过改变</p>
^{pr2}$
<p>到</p>
<pre><code>unhexsring = hex2str(hexstring) # -> bytes
</code></pre>
<p>但是,这会导致一个新的错误:</p>
<pre><code>unhexsring = zlib.decompress(unhexsring)
zlib.error: Error -3 while decompressing data: incorrect header check
</code></pre>
<p>这是因为这句话:</p>
<pre><code>hexstring = str(zlib.compress(hexstring.encode('utf-8')))
</code></pre>
<p>对<code>bytes</code>实例调用<code>str</code>不会将<code>bytes</code>转换为<code>str</code>,而是将字节<code>repr</code>转换为<code>str</code>。在</p>
<pre><code>>>> bs = 'Hello World'.encode('utf-8')
>>> print(repr(bs))
b'Hello World'
>>> s = str(bs)
>>> print(repr(s))
"b'Hello World'" # <- note the b....
</code></pre>
<p><code>str</code>转换在压缩数据的前面插入了一个'b',从而损坏了头。现在让我们将hexstring保留为bytes对象</p>
<pre><code>hexstring = zlib.compress(hexstring.encode('utf-8'))
</code></pre>
<p>但现在代码又引发了另一个例外:</p>
<pre><code>return binascii.hexlify(bytes(str.encode(s)))
TypeError: descriptor 'encode' requires a 'str' object but received a 'bytes'
</code></pre>
<p><code>s</code>现在是一个<code>bytes</code>对象,因此不需要尝试转换它(注意,<code>str.encode</code>无论如何都返回{<cd2>},因此即使<code>s</code>是字符串,<code>bytes</code>调用也是多余的)。在</p>
<p>{cd16>变成了</p>
<pre><code>def str2hex(s):
return binascii.hexlify(s)
</code></pre>
<p>现在又出现了另一个错误:</p>
<pre><code>unhexsring = str(zlib.decompress(unhexsring).encode('utf8'))
AttributeError: 'bytes' object has no attribute 'encode'
</code></pre>
<p><code>zlib.decompress</code>的输出是一个<code>bytes</code>对象,因此它已经被编码(假设它是一个字符串开头)。您想对其进行解码以获得<code>str</code>:</p>
<pre><code>unhexsring = zlib.decompress(unhexsring).decode('utf8')
</code></pre>
<p>这是可以作为脚本从命令提示符下运行的代码版本:</p>
<pre><code>import binascii
import random
import string
import zlib,gzip
import zlib,gzip
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.choice(string.ascii_letters) for _ in range(201))
if len(hexstring) > 200:
hexstring = zlib.compress(hexstring.encode('utf-8'))
print(hexstring)
hexstring = str2hex(hexstring)
ph = str(hexstring.decode('utf-8'))
print(ph)
#decompressing text
unhexsring = hex2str(hexstring)
if 'x' in str(unhexsring):
print('compressed')
unhexsring = zlib.decompress(unhexsring).decode('utf8')
print(unhexsring)
if __name__ == '__main__':
main()
</code></pre>