pyparsing:嵌套countArray?

时间:2013-09-15 02:27:29

标签: python pyparsing

这是我尝试使用pyparsing解析的DSL片段

我有一个格式为<keyword> 02 01 30 03 40 20 10的字符串
哪里
02是字符串的数量
01是string1的长度(以字节为单位)
30是string1本身
03是string2的长度(以字节为单位)
40 20 10是string2

如何使用pyparsing对此字符串进行标记?

1 个答案:

答案 0 :(得分:1)

所以这是一个数不清的阿雷?你试过了吗?

from pyparsing import Word,nums,alphas,countedArray

test = "key 02 01 30 03 40 20 10"

integer = Word(nums)

# each string is a countedArray of integers, and the data is a counted array
# of those, so...
lineExpr = Word(alphas)("keyword") + countedArray(countedArray(integer))("data")

# parse the test string, showing the keyworod, and list of lists for the data
print lineExpr.parseString(test).asList()

给出:

['key', [['30'], ['40', '20', '10']]]

命名结果还允许您按名称获取解析位:

result = lineExpr.parseString(test)
print result.keyword
print result.data

给出:

key
[[['30'], ['40', '20', '10']]]