python程序代码解析_如何解析代码(在Python中)?

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

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 Group中.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值