Adding external information to ParseResults before return

﹥>﹥吖頭↗ 提交于 2019-12-02 09:52:43

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')

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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!