我正在尝试解码绘图.io. 根据他们的documentation,这是“使用标准放气压缩”。在
我使用这个question中提供的代码来处理通货膨胀。在
import zlib
import base64
def decode_base64_and_inflate( b64string ):
decoded_data = base64.b64decode( b64string )
return zlib.decompress( decoded_data , -15)
示例输入文件:
^{pr2}$我是这样读的:
from xml.dom import minidom
from urllib.parse import unquote
xmldoc = minidom.parse('samplescratchpad.xml')
buildings = xmldoc.getElementsByTagName('mxlibrary')
# I know eval is bad, but this was being returned as '[...]' instead of
# just a list.
all_buildings = eval(buildings[0].firstChild.nodeValue)
for building in all_buildings:
print(type(decode_base64_and_inflate(building['xml'])))
print(decode_base64_and_inflate(building['xml']))
print(unquote(decode_base64_and_inflate(building['xml'])))
前两个print语句的输出是:
<class 'bytes'>
b'%3CmxGraphModel%3E%3Croot%3E%3CmxCell%20id%3D%220%22%2F%3E%3CmxCell%20id%3D%221%22%20parent%3D%220%22%2F%3E%3CmxCell%20id%3D%222%22%20value%3D%22%26lt%3Bdiv%20style%3D%26quot%3Bfont-size%3A%209px%3B%26quot%3B%26gt%3BAssembler%26lt%3B%2Fdiv%26gt%3B%26lt%3Bdiv%20style%3D%26quot%3Bfont-size%3A%209px%3B%26quot%3B%26gt%3B15%20x%2010%26lt%3B%2Fdiv%26gt%3B%22%20style%3D%22rounded%3D0%3BwhiteSpace%3Dwrap%3Bhtml%3D1%3BfontSize%3D9%3Bpoints%3D%5B%5B0%2C0.33%2C1%5D%2C%5B0%2C0.66%2C1%5D%2C%5B1%2C0.5%2C1%5D%2C%5B0.5%2C0.5%2C0%5D%5D%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20width%3D%22150%22%20height%3D%22100%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3C%2Froot%3E%3C%2FmxGraphModel%3E'
最后一次打印时,我尝试将上述内容转换为更标准的XML,但失败了:
File "test_deflate.py", line 36, in <module>
print(unquote(decode_base64_and_inflate(building['xml'])))
File "/usr/lib/python3.5/urllib/parse.py", line 537, in unquote
if '%' not in string:
TypeError: a bytes-like object is required, not 'str'
当我试图unquote
它时,如何修复这个问题,使我拥有的bytes对象(见前两个打印输出)正常工作?在
另外:我的eval
行上真的需要all_buildings =
吗?在
实际上,您已经把问题弄反了,因为错误消息具有误导性。在
您的参数是一个类似于}是一个不工作的类似于
bytes
的对象,但是unquote函数使用的是表达式'%' in string
,而{bytes
的对象。两个操作数都必须是bytes
,或者两者都必须是str
。在Python错误地告诉您将第一个操作数(
'%'
)更改为bytes
,但由于这是函数的硬编码部分,所以这是不可能的。您需要将另一个参数改为str
。在尝试替换
与
^{pr2}$这将把}。在
bytes
解码为UTF8编码的Unicode字符串(很可能是正确的编码),并生成一个可以传递给unquote()
的{Edit:Python使用此错误消息的原因是
in
运算符在内部是对第二个操作数的方法调用;也就是说,a in b
被计算为b.__contains__(a)
。因此,b
决定了a
允许的类型,而不是相反——这意味着Python将告诉您更改第一个操作数的类型,而不是告诉您更改第二个操作数的类型。在相关问题 更多 >
编程相关推荐