2015-12-12 41 views
1

我正在使用python pyparsing libary,其輸出似乎是元組。但是,當試圖訪問作爲元組時,我得到意想不到的結果。Python元組訪問問題?

>>> 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)]} 

爲什麼我得到意外?這裏發生了什麼?謝謝。

+1

您輸入了aaa嗎? type(aaa) – PyNEwbie

+1

>>> type(aaa) >>> dir(aaa) ['::','__class__','__delattr__','__doc__','__format__ 」, '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__', 'EEE'] >>> – PyNEwbie

+1

看到這個答案對一個類似問題:http://stackoverflow.com/questions/7045757/list-of-dictionaries-and-pyparsing/7047048#7047048可以將ParseResults對象視爲列表,字典或對象。或者你可以使用'asList()'或'asDict()'來轉換它們。但首先嚐試這些訪問:'aaa [0]','aaa ['eee']'和'aaa.eee'。我有些迷惑,你有一些沒有出現在列表中的命名結果中的值,以及爲什麼有一個名爲「::」的命名元素。但是這些都與這個問題相關。如果你打印出'aaa.dump()',你會看到更好的細節。 – PaulMcG

回答

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和這些其他的東西,所以你可以問他們是什麼類型(文字),並瞭解他們的內部魔術目錄(文字)有時答案不是很有幫助,但通常你不會通過詢問來破壞任何東西。

底線,它不會出現aaa是一個元組,我注意到它有一些方法與元組的方法相同,但它沒有一個元組的所有方法。

+0

謝謝,無論如何,我可以得到所有在aaa中的信息。就像也許轉換成json?我非常需要它所有的元素:鍵/值在元組中的位置?再次感謝。 – jazzblue

+2

可通過https://pythonhosted.org/pyparsing/在線查找類文檔,以及在https://pythonhosted.org/pyparsing/pyparsing.ParseResults-class上的ParseResults文檔。html – PaulMcG

+0

Pyparsing類也可以使用docstrings進行註釋,可以使用python的'help'命令訪問,如'help(Literal)'或'Help(Literal.parseString)'。這將爲您提供超出dir輸出的實際文檔。 – PaulMcG