【问题标题】:Create function calls to returned functions parser in PyParsing在 PyParsing 中创建对返回函数解析器的函数调用
【发布时间】:2015-06-17 17:44:06
【问题描述】:

我想解析可以调用其他函数“返回”的函数的函数调用:

thisReturnsFunction()()

我已经这样做了:

id = Regex(r'[_a-zA-Z][_a-zA-Z0-9]*')

funcal = Forward()

value = funcal | id

funcal << value + Literal("(").suppress() + Literal(")").suppress()

一不小心,Python 堆栈溢出,整个 Python 崩溃了。 我知道value是递归的并且无限匹配thisReturnsFunction("Hello!"),因为funcal是匹配的,因为value是数学的,因为funcal是匹配的......

如何避免这种情况并设计出有效的模式?

【问题讨论】:

    标签: python recursion pyparsing recursive-regex


    【解决方案1】:

    我不确定 Pyparsing 能否以“纯”方式解析高阶函数。但是有一些“hacky”方式:为函数创建标记,为标记添加处理程序并在处理程序中建立正确的语法结构。 示例(我还为函数参数添加了标记)

    from pyparsing import Forward, Literal, Regex, OneOrMore, Optional, Group, delimitedList
    
    def function_parser(s, loc, toks):
        if len(toks) <= 2:
            return [toks[0], list(toks[1])]
        else:
            return [function_parser(s, loc, toks[:len(toks)-1]), toks[-1]]
    
    id = Regex(r'[_a-zA-Z][_a-zA-Z0-9]*')
    comma = Literal(',')
    funcal = Forward()
    expression  =  funcal | id 
    function_args = Optional(Group(delimitedList(expression,comma)),[])
    funcal << id + OneOrMore(Literal("(").suppress() + function_args + Literal(")").suppress())
    
    funcal.setParseAction(function_parser)
    
    def test_print(string):
        l = funcal.parseString(string).asList()
        print(l)
    
    test_print('justFunction(arg)')
    test_print('justFunction(arg)',)
    test_print('thisReturnsFunction()()',)
    test_print('thisReturnsFunction(arg1, arg2)(arg3)')
    

    它产生:

    ['justFunction', ['arg']]
    ['justFunction', ['arg']]
    [['thisReturnsFunction', []], []]
    [['thisReturnsFunction', ['arg1', 'arg2']], ['arg3']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      相关资源
      最近更新 更多