我的 PyParsing 语法有以下测试代码:
from pyparsing import Word, nums, alphas, delimitedList, Group, oneOf
from pprint import pprint
field = Word(alphas)("field")
operator = oneOf("= +")("operator")
string_value = Word(alphas)("string")
int_value = Word(nums).setParseAction(lambda t: int(t[0]))("int")
value = (string_value | int_value )("value")
expression = Group(field + operator + value)("expression")
grammar = Group(delimitedList(expression, delim="&&"))("expr_list")
def test(s):
print "Parsing '{0}'".format(s)
tokenized = grammar.parseString(s)
for f in tokenized:
e = f.expression
pprint(dict(e.items()))
if __name__ == "__main__":
test("foo=1")
test("foo=1 && bar=2")
test("foobar=2 && snakes=4")
输出非常出乎意料 - 似乎我只得到最后一个表达式tokenized
:
Parsing 'foo=1'
{'field': 'foo', 'int': 1, 'operator': '=', 'value': 1}
Parsing 'foo=1 && bar=2'
{'field': 'bar', 'int': 2, 'operator': '=', 'value': 2}
Parsing 'foobar=2 && snakes=4'
{'field': 'snakes', 'int': 4, 'operator': '=', 'value': 4}
我该如何解决?