How to retrieve list of values from result object in PyParsing?

我只是一个虾纸丫 提交于 2019-12-06 10:48:59

Well done on using results names, they are incredibly helpful when accessing the parsed fields. But it sounds like you need to add a layer of structuring to your parser, so that each line gets its own data, name, etc. You can do that by just redefining Lines as:

Lines = OneOrMore(Group(Line) + LineEnd().suppress())

Now, if you print(result.dump()) you get:

[['1', '10', '0', 'T20'], ['1', '76', '0', 'T76']]
[0]:
  ['1', '10', '0', 'T20']
  - data: ['1', '10', '0']
  - name: 'T20'
[1]:
  ['1', '76', '0', 'T76']
  - data: ['1', '76', '0']
  - name: 'T76'

The output of dump() is not meant to be parsed to get the values, it is meant to help show you how the structured values can be retrieved. For instance, you can do:

print(result[1].data)
print(result[1].name)

and get

['1', '76', '0']
T76

or:

for parsed_line in result:
    print("{name}: {data}".format_map(parsed_line))

and get:

T20: ['1', '10', '0']
T76: ['1', '76', '0']
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!