這裏是展示如何捕獲解析表達式的位置,並使用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
此功能已被納入pyparsing,作爲助手函數'locatedExpr'。在這個例子中,'markedInteger'將被替換爲'locatedExpr(Word(nums))',並且不需要添加任何分析動作。 – PaulMcG 2014-11-20 22:50:06
如果輸入文本包含個字符,還要格外小心。默認情況下,pyparsing在開始解析之前會在輸入字符串中調用'string.expandtabs()',這將改變輸入內字符串的預期位置。要抑制這種默認行爲,請在調用expr.parseString(inputStringContainingTabs)之前調用'expr.parseWithTabs()'。 –
PaulMcG
2014-11-20 22:54:10