【问题标题】:using bz2.decompress in python,but the answers different [closed]在python中使用bz2.decompress,但答案不同[关闭]
【发布时间】:2014-12-16 11:25:45
【问题描述】:

我有一个这样的字符串:

un: 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
pw: 'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08'

这是我的代码:

un = re.search(r"un: '(.+)'",page).group(1)
bz2.decompress(un)

然后我使用bz2.decompress方法,它返回错误:

IOError: invalid data stream

我试试这个:

un = 'BZh91...\x084'
bz2.decompress(un)

它会返回正确的答案。

补充:这是我的完整代码。

#!/usr/bin/env python
import urllib
import re 
import bz2

def main():
    page=urllib.urlopen("http://www.pythonchallenge.com/pc/def/integrity.html").read()
    unstring = re.search(r"un: *'(.+)'",page).group(1)
    print unstring
    un = "BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084"
    #the string un is copied from output of 'print unstring'
    print bz2.decompress (un)
    print bz2.decompress (unstring)
if (__name__=="__main__"):
    main()

这是输出:

==== No Subprocess ====
>>> 
BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084
huge
Traceback (most recent call last):
  File "/home/terry/pythonchallage/pythonchallenge_8.py", line 16, in <module>
    main()
  File "/home/terry/pythonchallage/pythonchallenge_8.py", line 14, in main
    print bz2.decompress (unstring)
IOError: invalid data stream
>>> 

【问题讨论】:

  • prin(repr(un)) 显示什么?那些 \xhh 是转义实际字节还是每个 4 个字符长?
  • 我猜你的 RE 同时采用了 unpw 值,而 pw: 在中间。解压前尝试打印一下。
  • 顺便说一句,我刚刚试过,pw 解压缩正确,但un 是错误的。也许你有一个错字......
  • 您给我们的示例帖子无效。
  • 离题了,但是您是否注意到您刚刚在 Internet 上发布了您的密码? (pw 代表 密码,不是吗?)

标签: python bzip2 compression


【解决方案1】:

您有 字符串文字,其中每个 \xhh 值是 4 个文字字符,而不是字节转义。

如果是这样,您首先需要告诉 Python 来解释这些:

bz2.decompress(un.decode('string_escape'))

演示:

>>> unstring = r'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
>>> print unstring
BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084
>>> unstring
'BZh91AY&SYA\\xaf\\x82\\r\\x00\\x00\\x01\\x01\\x80\\x02\\xc0\\x02\\x00 \\x00!\\x9ah3M\\x07<]\\xc9\\x14\\xe1BA\\x06\\xbe\\x084'
>>> import bz2
>>> bz2.decompress(unstring)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: invalid data stream
>>> bz2.decompress(unstring.decode('string_escape'))
'huge'

【讨论】:

    【解决方案2】:

    正如Martijn所指出的,数据实际上是无效的,所以它不会解压缩。

    除此之外,假设您的问题中没有错字,这是另一个潜在问题:您的正则表达式模式期望在un: 之后有一个空格,但您的示例字符串中没有这样的空格。您可以将正则表达式更改为r"un: *'(.+)'",这将允许:' 之间有零个或多个空格。

    【讨论】:

    • 数据流是无效的。
    • @MartijnPieters:就是这样。更新了答案。
    猜你喜欢
    • 2014-11-16
    • 2021-12-04
    • 2018-10-18
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2022-01-05
    相关资源
    最近更新 更多