Pyparsing令牌源范围

2024-03-28 13:02:46 发布

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

如何在Pyparsing中以编程方式提取语法规则匹配的源范围(开始和结束位置)?我不能将setParseAction用于这个(子)规则,因为我正在检查另一个回调中的解析树内容,该回调反过来指定为ParseAction。我还缺少了一个函数来打印由parseString()返回的内容,其方式类似于pprint。我知道toList(),但我不确定是否有兴趣的信息,比如上下文,被这个成员剥离了。在


Tags: 函数信息内容规则编程方式语法成员
1条回答
网友
1楼 · 发布于 2024-03-28 13:02:46

下面是一些示例代码,演示如何捕获已解析表达式的位置,并使用dump()列出已解析的数据和命名结果:

from pyparsing import *

# use an Empty to define a null token that just records its
# own location in the input string
locnMarker = Empty().leaveWhitespace().setParseAction(lambda s,l,t: l)

# define a example expression and save the start and end locations
markedInteger = locnMarker + Word(nums)('value') + locnMarker

# assign named results for the start and end values,
# and pop them out of the actual list of tokens
def markStartAndEnd(s,l,t):
    t['start'],t['end'] = t.pop(0),t.pop(-1)
markedInteger.setParseAction(markStartAndEnd)

# find all integers in the source string, and print
# their value, start, and end locations; use dump()
# to show the parsed tokens and any named results
source = "ljsdlj2342 sadlsfj132 sldfj12321 sldkjfsldj 1232"
for integer in markedInteger.searchString(source):
    print integer.dump()

印刷品:

^{pr2}$

相关问题 更多 >