python - 如何解析代码(在 Python 中)?

标签 python parsing data-structures

我需要解析一些特殊的数据结构。它们采用某种类似于 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 代码。

有没有像这样解析文件的 pythonic 方式?
您将如何解析它?

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

最佳答案

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

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 定义了一个“组”类,用于为解析的标记赋予结构——注意条目中的值列表是如何分组的,因为列表表达式包含在 pyparsing 组中。)

关于python - 如何解析代码(在 Python 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5217386/

相关文章:

python - 使用 BeautifulSoup 解析 HTML 时缺少特殊字符和标签

mysql - xslt-processor 在一个数据集上返回最佳结果,在另一个数据集上没有返回结果

python - 检查Python中的函数是否使用了print-function

java - 通过伪代码解析大O分析的代码

c - 求最小总和使得没有两个元素相邻

data-structures - Ada- 'at' 和 'range' 是什么意思/做什么?

algorithm - sharir kosaraju 算法和顶点

python - brew 安装 python3 后出现 SSL 错误

python - 在 python 中使用变量作为新文件名称的一部分

python - Django-recaptcha 总是显示 "This field is required.",即使它在那里