Skip to content Skip to sidebar Skip to footer

Adding External Information To ParseResults Before Return

I want to add external information to ParseResults before return. I return the results of parsing as asXML(). The external data represented as dictionary so as to parsed as XML in

Solution 1:

One problem is this fragment:

external_data = {'name':'omar', 'age':'40'}
return t + toks + ParseResults(external_data)

ParseResults will take a dict as a constructor argument, but I don't think it will do what you want - it just assigns the dict as it's 0'th element, and does not assign any results names.

You can assign named values into a ParseResults by using its dict-style assignment:

pr = ParseResults(['omar','40'])
for k,v in external_data.items():
    pr[k] = v

See if this gets you closer to your desired format.

EDIT: Hmm, it seems asXML is more fussy about how named results get added to the ParseResults, than just setting the name. This will work better:

def addNamedResult(pr, value, name):
    addpr = ParseResults([value])
    addpr[name] = value
    pr += addpr

And then in your parse action, add the values with their names using:

addNamedResult(toks, 'omar', 'name')
addNamedResult(toks, '40', 'age')

Solution 2:

Thanks very much Paul. I modified your function to add a dictionary of data

...
external_data = {'name':'omar', 'age':'40'}
return t + toks +  addDicResult(external_data)
...

def addDicResult(dict):
     pr = ParseResults([])
     for k, v in dict.items():
         addpr = ParseResults([v])
         addpr[k] = v
         pr += addpr
     return pr

The output
<main>
  <A>100</A>
  <B>200</B>
  <C>10</C>
  <ex>XXX</ex>
  <color>green</color>
  <age>40</age>
  <name>omar</name>
</main>

Post a Comment for "Adding External Information To ParseResults Before Return"