用于解析块的Python实用程序?

时间:2015-05-07 21:43:07

标签: python parsing

我有一个类似于:

的文件
databaseCons = {
    main = {
        database = "readable_name",
        hostname = "hostdb1.serv.com",
        instances= {
            slaves = {
                conns = "8"
            }
        }
        maxconns = "5",
        user = "user",
        pass = "pass"
    }
}

所以,我想做的是将其解析为dict个子dict,如:

{'main': {'database': 'readable_name', 'hostname': 'hostdb1.serv.com', 'maxconns': '5', 'instances': {'slave': {'maxCount': '8'}}, 'user': 'user', 'pass': 'pass'}}

我认为以上内容是有道理的......但如果没有,请随时编辑。基本上我想要相当于:

conns = '8'

slave = dict()
slave['maxCount'] = conns

instances = dict()
instances['slave'] = slave

database = 'readable_name'
hostname = 'hostdb1.serv.com'
maxconns = '5'
user = 'user'
pas = 'pass'
main = dict()
main['database'] = database
main['hostname'] = hostname
main['instances'] = instances
main['maxconns'] = maxconns
main['user'] = user
main['pass'] = pas

databaseCons = dict()
databaseCons['main'] = main

有没有可以处理这种解析的模块?即使我上面提出的建议看起来也很混乱......我必须有更好的方式。

1 个答案:

答案 0 :(得分:2)

以下是配置文件的pyparsing解析器:

from pyparsing import *

def to_dict(t):
    return {k:v for k,v in t}

series = Forward()
struct = Suppress('{') + series + Suppress('}')
value = quotedString.setParseAction(removeQuotes) | struct
token = Word(alphanums)
assignment = Group(token + Suppress('=') + value + Suppress(Optional(",")))
series << ZeroOrMore(assignment).setParseAction(to_dict)
language = series + stringEnd

def config_file_to_dict(filename):
    return language.parseFile(filename)[0]

if __name__=="__main__":
    from pprint import pprint
    pprint(config_file_to_dict('config.txt'))