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