在pyparsing中检测变量类型

时间:2012-09-07 13:17:38

标签: python pyparsing

我有这样的令牌序列:

TokenName(alphanum) value(printable) value(printable, optional) value(printable, optional) Literal(';')

通过示例:

Token1 "stringValue with escaped data eg: \" in it";
Token2 12;
Token3 0xaaaa; // and hex string indicated by 0x
Token4 "value1" 2 0xbbcc;

结果我除了:

[
    ['Token1', 'stringValue with escaped data eg: " in it'],
    ['Token2', 12],
    ['Token3', '0xaaaa'],
    ['Token4', ['value1', 2, '0xbbcc']],
]

现在我有这样的事情:

import pyparsing as p
non_semi = ''.join(c for c in p.printables if c != ';')
semi = p.Literal(';').suppress()

single_value = p.Word(non_semi) + semi
multi_value = p.Group(
    p.Word(non_semi) +
    p.Word(non_semi) +
    p.Optional(p.Word(non_semi)) +
    semi
)

value = single_value | multi_value
assignment = p.Group(p.Word(p.alphanum) + value)

bnf = p.Group(p.OneOrMore(assignment))
bnf.ignore(p.cStyleComment)

但是这段代码不会将12更改为int(12)并且还会在字符串中获得"个字符,pyparsing可以处理此值转换吗?

修改

好的,我知道如何处理字符串:QuotedString有很多帮助

1 个答案:

答案 0 :(得分:2)

好的,我找到了答案:

处理字符串:QuotedString

对于int和其他转换的处理,有一个令牌def的setParseAction方法,可以采取例如。 lambda s, l, t: int(s) param女巫会做的伎俩