【问题标题】:How to parse code (in Python)?如何解析代码(在 Python 中)?
【发布时间】:2011-03-07 08:24:16
【问题描述】:

我需要解析一些特殊的数据结构。它们采用某种类似于 C 的格式,大致如下所示:

Group("GroupName") {
    /* C-Style comment */
    Group("AnotherGroupName") {
        Entry("some","variables",0,3.141);
        Entry("other","variables",1,2.718);
    }
    Entry("linebreaks",
          "allowed",
          3,
          1.414
         );
}

我可以想出几种方法来解决这个问题。我可以使用正则表达式“标记”代码。我可以一次读取一个字符的代码并使用状态机来构建我的数据结构。我可以摆脱逗号换行符并逐行阅读。我可以编写一些转换脚本,将此代码转换为可执行的 Python 代码。

有没有一种很好的 Python 方法来解析这样的文件?
你将如何解析它?

这是一个关于如何解析字符串的更一般的问题,而不是关于这种特定文件格式的问题。

【问题讨论】:

标签: python parsing data-structures


【解决方案1】:

使用 pyparsing(Mark Tolonen,当您的帖子通过时,我正要点击“提交帖子”),这非常简单 - 请参阅下面代码中嵌入的 cmets:

data = """Group("GroupName") { 
    /* C-Style comment */ 
    Group("AnotherGroupName") { 
        Entry("some","variables",0,3.141); 
        Entry("other","variables",1,2.718); 
    } 
    Entry("linebreaks", 
          "allowed", 
          3, 
          1.414 
         ); 
} """

from pyparsing import *

# define basic punctuation and data types
LBRACE,RBRACE,LPAREN,RPAREN,SEMI = map(Suppress,"{}();")
GROUP = Keyword("Group")
ENTRY = Keyword("Entry")

# use parse actions to do parse-time conversion of values
real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t:float(t[0]))
integer = Regex(r"[+-]?\d+").setParseAction(lambda t:int(t[0]))

# parses a string enclosed in quotes, but strips off the quotes at parse time
string = QuotedString('"')

# define structure expressions
value = string | real | integer
entry = Group(ENTRY + LPAREN + Group(Optional(delimitedList(value)))) + RPAREN + SEMI

# since Groups can contain Groups, need to use a Forward to define recursive expression
group = Forward()
group << Group(GROUP + LPAREN + string("name") + RPAREN + 
            LBRACE + Group(ZeroOrMore(group | entry))("body") + RBRACE)

# ignore C style comments wherever they occur
group.ignore(cStyleComment)

# parse the sample text
result = group.parseString(data)

# print out the tokens as a nice indented list using pprint
from pprint import pprint
pprint(result.asList())

打印

[['Group',
  'GroupName',
  [['Group',
    'AnotherGroupName',
    [['Entry', ['some', 'variables', 0, 3.141]],
     ['Entry', ['other', 'variables', 1, 2.718]]]],
   ['Entry', ['linebreaks', 'allowed', 3, 1.4139999999999999]]]]]

(不幸的是,由于 pyparsing 定义了一个“Group”类,用于将结构传递给已解析的标记 - 请注意条目中的值列表如何分组,因为列表表达式包含在 pyparsing 组中。)

【讨论】:

  • 你刚刚在 O'Reilly 书店赚了 10 美元!
【解决方案2】:

查看pyparsing。它有很多parsing examples

【讨论】:

    【解决方案3】:

    取决于您需要的频率以及语法是否保持不变。如果答案是“经常”和“或多或少是”,那么我会寻找一种表达语法的方法,并使用PyPEGLEPL 之类的工具为该语言编写特定的解析器。定义解析器规则是一项艰巨的工作,因此除非您经常需要解析相同类型的文件,否则它可能不一定有效。

    但是,如果您查看 PyPEG 页面,它会告诉您如何将解析后的数据输出到 XML,因此如果该工具无法为您提供足够的功能,您可以使用它来生成 XML,然后使用例如lxml 解析xml。

    【讨论】:

      猜你喜欢
      • 2019-09-22
      • 2016-09-10
      • 2011-06-20
      • 2023-03-27
      • 2020-08-04
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多