【问题标题】:Advice on Python Parser Generators关于 Python 解析器生成器的建议
【发布时间】:2009-11-21 17:50:00
【问题描述】:

我接到了一项任务,我必须为一种简单的类 C 语言创建解析器。我可以使用任何我想创建解析器的编程语言和工具,但我同时也在学习 Python,所以它是我的首选。

我的解析器必须遵守一些限制。首先,它必须能够读取包含以下信息的文本文件:

kind1 : spelling1
kind2 : spelling2
kind3 : spelling3
      .
      .
      .
kindn : spellingn

每种类型和拼写都指代该语言的标记类型和值。该文件是通过语言的词法分析器放置代码示例的结果。

其次,我必须能够自定义解析器的输出。理想情况下,我想输出一个将 kind:spelling 列表转换为另一个标记序列的文件,该标记将传递给语言的编译器以转换为 MIPS 汇编代码。这是我希望解析器能够产生的那种东西的一个小例子:

%function int test
  %variable int x
  %variable int y
%begin
  %if %id y , %id x > %do
  %begin
    %return %num 0
  %end
  %return %num 1
%end

如果有人可以就现有的 Python 解析器生成器向我提供建议,并且如果我能够实现我在​​上述示例中寻找的那种东西,那将是一个很大的帮助。

【问题讨论】:

    标签: python parser-generator


    【解决方案1】:

    PyParsing 是一个生成解析器的python工具。有一个lot of interesting examples。

    容易上手:

    from pyparsing import Word, alphas
    
    # define grammar
    greet = Word( alphas ) + "," + Word( alphas ) + "!"
    
    # input string
    hello = "Hello, World!"
    
    # parse input string
    print hello, "->", greet.parseString( hello )
    

    【讨论】:

    • PyParsing 是一个解析器组合库,而不是解析器 generator ;-)
    【解决方案2】:

    我建议你查看 Lark:https://github.com/erezsh/lark

    它可以解析所有上下文无关的语法,它会自动构建一个 AST(带有行号和列号),并且它接受 EBNF 格式的语法,它易于编写并且被认为是标准的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2012-09-03
      相关资源
      最近更新 更多