首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中基于“扩展”模板的INI文件解析

Python中基于“扩展”模板的INI文件解析
EN

Stack Overflow用户
提问于 2017-11-08 19:08:24
回答 1查看 241关注 0票数 0

我需要解析(并提供给数据库)这样的配置文件(实际上它是Asterisksip.conf):

代码语言:javascript
复制
[client-template](!,natted-template)
foo=foovalue
moo=moovalue

[client](client-template)
bar=barvalue

这种语法意味着client-template本身就是一个基于natted-template (在别处定义)的模板(因为括号中有! )。而client是一个基于client-template的对象定义。

我可以使用ConfigParser,但看起来我需要更强大或更定制的东西?

EN

回答 1

Stack Overflow用户

发布于 2017-11-09 22:41:07

好了,现在我已经尝试过pyparsing

代码语言:javascript
复制
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())

这是解决方案的一部分(这是到目前为止还没有意识到的评论),但我可以继续。

如果有更优雅的解决方案,请让我知道。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47178150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档