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()
下面是一些示例代码,演示如何捕获已解析表达式的位置,并使用
dump()
列出已解析的数据和命名结果:印刷品:
^{pr2}$相关问题 更多 >
编程相关推荐