2

如何在 Pyparsing 中以编程方式提取语法规则匹配的源范围(开始和结束位置)?我不能使用setParseAction这个(子)规则,因为我正在检查另一个回调中的解析树内容,而另一个回调又指定为ParseAction. 我还缺少一个以类似于返回的内容的人道方式打印的功能。我知道,但我不确定有趣的信息,例如上下文,是否被这个成员剥夺了。pprintparseString()toList()

4

1 回答 1

3

下面是一些示例代码,展示了如何捕获已解析表达式的位置,并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()

印刷:

['2342']
- end: 11
- start: 6
- value: 2342
['132']
- end: 22
- start: 18
- value: 132
['12321']
- end: 33
- start: 27
- value: 12321
['1232']
- end: 48
- start: 44
- value: 1232
于 2013-04-24T06:02:48.817 回答