How can I get a token instead of a string?

I have the following syntax:

kv = Word(alphanums + '_') | QuotedString('"', escQuote="\\") | QuotedString("'", escQuote="\\")
kv = kv.setResultsName('literal', listAllMatches=True)
cskv = kv + Optional(ZeroOrMore(Suppress(',') + kv))  # comma separated kv

and with this example:

>>> res=cskv.parseString('a,b,c,d,e')
>>> res
(['a', 'b', 'c', 'd', 'e'], {'literal': [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)]})
>>> res[0]
'a'
>>> type(res[0])
<type 'str'>

Note:

>>> type(res[0])
<type 'str'>

I really want him to be ParseResultsinstead of a string so that I can go res[0].getName()to him, and hopefully I should get one literal.

Second question: how can I get the index of some token?

let's say I want to know the index literal d, it must return 3.

this is trivial in this example, since I have only one type of token, but in my problem I need to know the relative position of different types of tokens so that it helps during processing.

any way to achieve them?

EDIT:

I do not know why my question is so confusing, and why people do not focus on my example, and not on my question. following explanation:

pyparsing , , , , , - , , ( , ):

variable = string

- , , , , , ( , , ).

:

expr = Word(alphanums+'_')('leftval') + '=' + Word(alphanums+'_')('rightval')

, :

In [3]: res = expr.parseString('variable = string')

In [4]: res
Out[4]: (['variable', '=', 'string'], {'rightval': [('string', 2)], 'leftval': [('variable', 0)]})

:

In [5]: res[0]
Out[5]: 'variable'

In [6]: type(res[0])
Out[6]: str

res . , , , , leftval.

, __repr__ of res :

, - , res.

, ?

. .

+4
2

,

from pyparsing import Word, alphas,alphanums,QuotedString,Optional,ZeroOrMore,Suppress

kv = Word(alphanums + '_') | QuotedString('"', escQuote="\\") | QuotedString("'", escQuote="\\")
kv = kv.setResultsName('literal', listAllMatches=True)
cskv = kv + Optional(ZeroOrMore(Suppress(',') + kv))  # comma separated kv
tokens = cskv.parseString("a,b,c,d,e")

#you can use asDict to get a dictionary mapping names to values
print tokens.asDict()

#or you can get it as xml and parse the xml
import re
xml_result = tokens.asXML()
for tok in tokens:
    needle = "\<([^\>]+)\>\s*%s\s*\<\/"%tok
    print tok, "=", re.search(needle,xml_result).groups()[0]

... Im ... ...

import ast
parsed_values,meta_data = ast.literal_eval(repr(tokens))
print parsed_values # ['a', 'b', 'c', 'd', 'e']
print meta_data # {'literal': [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)]}
0

pyparsing delimitedList, , , .

:

- ','. , comb = True . , ; .

, , ParseResult:

csvExpr = delimitedList()

parsed = csvExpr.parseString("a,b,c,d,e")

print(type(parsed)) # output: <class 'pyparsing.ParseResults'>
0

All Articles