首页 > 解决方案 > 如果组件解析器有结果名称,为什么结果元素是 ParseResults 类型?

问题描述

我不清楚为什么解析结果列表有时包含 ParseResults 元素而不是字符串。

例如:

from pyparsing import *

text = "pfx01ABC"

# nested result name
pfx = Literal("pfx")("prefix")
combined = Combine(pfx + Word(alphanums))("combined")

combined.runTests(text)
res = combined.parseString(text)
print("type(res[0]):", type(res[0]))
print('type(res["combined"]):', type(res["combined"]))

# doubly nested result names
infix = Word(nums)("infix")
pfx = Combine(Literal("pfx") + infix)("prefix")
combined = Combine(pfx + Word(alphas))("combined")

combined.runTests(text)
res = combined.parseString(text)
print("type(res[0]):", type(res[0]))
print('type(res["combined"]):', type(res["combined"]))
print('type(res["combined"]["prefix"]):', type(res["combined"]["prefix"]))

# no nested result names
pfx = Literal("pfx") + Word(nums)
combined = Combine(pfx + Word(alphas))("combined")

combined.runTests(text)
res = combined.parseString(text)
print("type(res[0]):", type(res[0]))
print('type(res["combined"]):', type(res["combined"]))

生产

pfx01ABC
[['pfx01ABC']]
- combined: ['pfx01ABC']
  - prefix: 'pfx'

type(res[0]): <class 'pyparsing.ParseResults'>
type(res["combined"]): <class 'pyparsing.ParseResults'>

pfx01ABC
[['pfx01ABC']]
- combined: ['pfx01ABC']
  - prefix: ['pfx01']
    - infix: '01'

type(res[0]): <class 'pyparsing.ParseResults'>
type(res["combined"]): <class 'pyparsing.ParseResults'>
type(res["combined"]["prefix"]): <class 'pyparsing.ParseResults'>

pfx01ABC
['pfx01ABC']
- combined: 'pfx01ABC'

type(res[0]): <class 'str'>
type(res["combined"]): <class 'str'>

是因为结果名称与嵌套解析器一起存储而不是全局存储吗?

在双重嵌套结果名称的情况下,结果具有与在单个嵌套结果名称的情况下相同数量的封闭方括号。假设上述情况,我的期望是带有一组附加方括号的结果。为什么不是这样?

标签: pythonpyparsing

解决方案


推荐阅读