如果组件解析器有一个结果名,为什么ParseResults类型的结果元素是?

2024-09-29 21:36:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我不清楚为什么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'>

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

对于双重嵌套的结果名,结果具有与单个嵌套结果名相同数量的方括号。假设上述情况,我的预期结果是一组附加的方括号。为什么不是这样


Tags: textprefixtyperespyparsingclasswordnested

热门问题