【问题标题】:Pyparsing Identifiers pushed onto the stack twicePyparsing 标识符被推入堆栈两次
【发布时间】:2014-03-03 14:02:55
【问题描述】:

我不知道为什么会这样,但是我的ident 终端被推入堆栈两次。这不会发生在我的语法中的任何其他终端上。我所有的 save_xxx_function 只需将转换后的值添加到 stack。对于save_ident_function,我只是将第一个令牌添加到堆栈中,而不进行任何处理。

# Terminal symbols defined here....
ident = Word(alphas, alphanums + '_')

expr = Forward()
atom = Forward()
arg = expr
args = delimitedList(arg)

func_call = (ident + lbrace + Optional(args) + rbrace).setParseAction(save_token_function)

bracketed_list = (lbracket + Optional(delimitedList(atom)) +    rbracket).setParseAction(save_list_function)

atom << ( bracketed_list | func_call | (lbrace + expr.suppress() + rbrace)  |     decimal.setParseAction(save_decimal_function) | integer.setParseAction(save_int_function) | ident.setParseAction(save_ident_function) | sglQuotedString.setParseAction(save_string_function) )

factor = Forward()

factor << atom + ZeroOrMore( (exponent + factor).setParseAction(save_token_function) )

term = factor + ZeroOrMore( (multdivide + factor).setParseAction(save_token_function) )

rel_term = term + ZeroOrMore( (relational + term).setParseAction(save_token_function) )

expr << rel_term + ZeroOrMore( (plusminus + rel_term).setParseAction(save_token_function) )

# Define the grammar now ...
grammar = expr + StringEnd()

# function to just drop the identifier on to the stack
def save_ident_function(s, l, tokens):
token = tokens[0]
stack.append(token)

我得到以下表达式的以下堆栈: 2 * 3 => [2, 3, '*'] x * 2 => ['x', 'x', 2, '*']

【问题讨论】:

    标签: python stack pyparsing


    【解决方案1】:

    好的,所以我在这里遇到的问题是我正在重新使用ident 终端。我将ident 终端用于变量,但我也将它用于func_call(函数调用)非终端。我不确定这是否只是整体上重复使用这样的终端的不好做法,或者在识别过程中他们是否根据语法规则调用解析操作。

    解决方法很简单...只需为 func_call 名称使用不同的终端。

    ident = Word(alphas, alphanums + '_')
    # Add a non-terminal for the name of a function
    func_name = Word(alphas, alphanums + '_')
    
    # Change func_call grammar rule to use func_name for the name instead of ident
    func_call = (func_name + lbrace + Optional(args) + rbrace).setParseAction(save_token_function)
    

    此外,func_name 没有解析操作,func_call 有。这也可能使事情变得复杂。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 1970-01-01
      • 2011-04-22
      • 2018-12-30
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多