我需要解析(并提供给数据库)这样的配置文件(实际上它是Asterisk的sip.conf):
[client-template](!,natted-template)
foo=foovalue
moo=moovalue
[client](client-template)
bar=barvalue这种语法意味着client-template本身就是一个基于natted-template (在别处定义)的模板(因为括号中有! )。而client是一个基于client-template的对象定义。
我可以使用ConfigParser,但看起来我需要更强大或更定制的东西?
发布于 2017-11-09 22:41:07
好了,现在我已经尝试过pyparsing了
import pyparsing as pp
filename = 'client.conf'
nametag = pp.Word(pp.alphanums + "-_")
variable = pp.Word(pp.alphanums)
value = pp.Word(pp.alphanums + "=")
vardef = pp.Group(variable('variable') + pp.Literal("=").suppress() + value('value'))
vardefs = pp.Group(pp.ZeroOrMore(vardef))('vardefs')
section = pp.Group(pp.Literal("[").suppress() \
+ nametag('objectname') \
+ pp.Literal("]").suppress() \
+ pp.Optional(
pp.Literal("(").suppress() \
+ pp.Optional("!")('istemplate')
+ pp.ZeroOrMore(pp.Optional(",").suppress() + nametag)('parenttemplates') \
+ pp.Literal(")").suppress()
) \
+ vardefs)
section = section + pp.Optional(pp.SkipTo(section)).suppress()
section_group = pp.Group(section + pp.ZeroOrMore(section))('sections')
config = (pp.SkipTo(section_group).suppress() \
+ section_group)
# res = config.parseString(open(filename).read())这是解决方案的一部分(这是到目前为止还没有意识到的评论),但我可以继续。
如果有更优雅的解决方案,请让我知道。
https://stackoverflow.com/questions/47178150
复制相似问题