gpt4 book ai didi

python - 在 pyparsing 中获取等同于 asXML() 的数据结构?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:18 25 4
gpt4 key购买 nike

我了解到在 pyparsing 中,您可以通过这样做来命名元素/组/节点:

token = pyparsing.Literal("Foobar")("element_name_here")

所以,我做了一个示例程序来测试它:

import pyparsing as pp

Prefix = pp.Word(pp.nums)("Prefix")
Name = pp.Literal("FOOBAR")("Name")
Modifier = pp.Word(pp.alphas)("Modifier")
Modifier_Group = pp.Group(pp.OneOrMore(Modifier))("Modifier_Group")
Sentence = pp.Group(pp.Optional(Prefix) + Name + Modifier_Group)("Sentence")

out = Sentence.parseString("123 FOOBAR testA testB")

然后,我尝试使用这些命名标记获取输出。

我试过这个:

>>> print out
[['123', 'FOOBAR', ['testA', 'testB']]]

...但这并没有让我得到代币名称。

然后我尝试执行以下操作:

>>> print out.items()
[('Sentence', (['123', 'FOOBAR', (['testA', 'testB'], {'Modifier': [('testA', 0),
('testB', 1)]})], {'Modifier_Group': [((['testA', 'testB'], {'Modifier': [('testA', 0),
('testB', 1)]}), 2)], 'Prefix': [('123', 0)], 'Name': [('FOOBAR', 1)]}))]

>>> print dict(out)

{'Sentence': (['123', 'FOOBAR', (['testA', 'testB'], {'Modifier': [('testA', 0),
('testB', 1)]})], {'Modifier_Group': [((['testA', 'testB'], {'Modifier': [('testA', 0),
('testB', 1)]}), 2)], 'Prefix': [('123', 0)], 'Name': [('FOOBAR', 1)]})}

>>> import collections
>>> print collections.OrderedDict(out)
OrderedDict([('Sentence', (['123', 'FOOBAR', (['testA', 'testB'], {'Modifier': [
('testA', 0), ('testB', 1)]})], {'Modifier_Group': [((['testA', 'testB'],
{'Modifier': [('testA', 0), ('testB', 1)]}), 2)], 'Prefix': [('123', 0)],
'Name': [('FOOBAR', 1)]}))])

...但它们包含字典、列表和元组的特殊混合体,我不知道如何解析它们。然后,我尝试这样做:

>>> print out.asXML()
<Sentence>
<Sentence>
<Prefix>123</Prefix>
<Name>FOOBAR</Name>
<Modifier_Group>
<Modifier>testA</Modifier>
<Modifier>testB</Modifier>
</Modifier_Group>
</Sentence>
</Sentence>

...这让我得到了我想要的东西,除了它是在 XML 中,而不是我可以轻松操作的 python 数据结构。有没有什么方法可以获得这样的数据结构(无需解析 XML)?

我确实找到了一个返回 nested dict 的解决方案,但 python 中的字典是无序的,(我希望 token 按顺序排列),所以这不是我的解决方案。

最佳答案

Pyparsing 返回一个已经为您提供该结构的 ParseResults 对象。您可以通过打印 out.dump() 来可视化您的句子结构:

>>> print out.dump()
[['123', 'FOOBAR', ['testA', 'testB']]]
- Sentence: ['123', 'FOOBAR', ['testA', 'testB']]
- Modifier_Group: ['testA', 'testB']
- Modifier: testB
- Name: FOOBAR
- Prefix: 123

您可以像访问字典中的键一样访问这些元素:

>>> print out.Sentence.keys()
['Modifier_Group', 'Prefix', 'Name']
>>> print out.Sentence['Prefix']
123

或作为对象的属性:

>>> print out.Sentence.Name
FOOBAR
>>> print out.Sentence.Prefix
123

关于python - 在 pyparsing 中获取等同于 asXML() 的数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11593908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com