Pyparsing is a rollback from unreadable and fragile regex processors. The parsing example below handles your declared format, as well as all sorts of extra spaces and arbitrary order of assignment expressions. Just as you used named groups in your regular expression, pyparsing supports result names so that you can access the parsed data using the dict syntax or attribute (data ['Lint'] or data.Lint).
from pyparsing import Suppress, Word, nums, oneOf, Regex, ZeroOrMore, Optional # define basic punctuation EQ,LPAR,RPAR,LBRACK,RBRACK = map(Suppress,"=()[]") # numeric values integer = Word(nums).setParseAction(lambda t : int(t[0])) real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t : float(t[0])) # id and assignment fields idRef = LBRACK + integer("id") + RBRACK typesep = LPAR + oneOf("DG") + RPAR lExpr = 'L' + EQ + integer("Lint") rExpr = 'R' + EQ + integer("Rint") pExpr = 'p' + EQ + real("pFloat") eExpr = 'e' + EQ + integer("Eint") nExpr = 'n' + EQ + integer("Nint") # accept assignments in any order, with or without leading (D) or (G) assignment = lExpr | rExpr | pExpr | eExpr | nExpr line = idRef + lExpr + ZeroOrMore(Optional(typesep) + assignment) # test the parser text = "[ 0 ] L= 9 (D) R= 14 (D) p= 0.0347222 e= 10 n= 34" data = line.parseString(text) print data.dump() # prints # [0, 'L', 9, 'D', 'R', 14, 'D', 'p', 0.034722200000000002, 'e', 10, 'n', 34] # - Eint: 10 # - Lint: 9 # - Nint: 34 # - Rint: 14 # - id: 0 # - pFloat: 0.0347222
In addition, the string-> int or string-> float conversion is performed during parsing in the parsing actions, so that later the values ββare already in a useful form. (The idea in pyparsing is that when analyzing these expressions you know that a word consisting of numeric digits - or Word(nums) - will safely convert to int, so why not do the conversion right then instead of just return to string matching and the need to reprogram the string sequence, trying to determine which ones are integers, floats, etc.?)
source share