我正在使用python pyparsing libary,其输出似乎是元组。但是,当尝试以元组形式访问时,我会得到意想不到的结果。
>>> from pyparsing import *
>>> aaa = (Literal('xxx') + SkipTo(':') + Literal(':')('::') + Word(nums)('eee')).parseString('xxx : 123')
>>> aaa
(['xxx', '', ':', '123'], {'eee': [('123', 3)], '::': [(':', 2)]})
这是奇怪的:
>>> aaa[0]
'xxx'
>>> aaa[1]
''
我希望aaa[0]
成为列表:
['xxx', '', ':', '123']
和aaa [1] - 字典:
{'eee': [('123', 3)], '::': [(':', 2)]}
为什么我会意外?这里发生了什么?感谢。
答案 0 :(得分:3)
Python有一些很好的内省能力。要确定什么是问题
>>>type(aaa)
<class 'pyparsing.ParseResults'>
你可以用它做什么,方法和属性
>>>dir(aaa)
['::', '__class__', '__delattr__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__', 'eee']
我看到它有一个get方法,所以
for each in aaa:
type(each), each, len(each)
<type 'str'>
for each in aaa:
type(each), each, len(each)
(<type 'str'>, 'xxx', 3)
(<type 'str'>, '', 0)
(<type 'str'>, ':', 1)
(<type 'str'>, '123', 3)
现在是时候阅读文档
了我会注意到你使用pyparsing方法创建了xxx和其他东西,所以你可以问它们是什么类型(Literal)并了解它们的内部魔法目录(Literal)有时答案不是那么有用,但是通常你不会通过询问来打破任何事情。
从底线看,aaa似乎不是一个元组,我注意到它有一些与元组方法相同的方法,但它没有元组的所有方法。