gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:36:22 28 4
gpt4 key购买 nike

我有一个文件开头是这样的:

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

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

{'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

是否有任何模块可以处理这种解析?甚至我上面建议的内容看起来也很困惑。我一定有更好的方法。

最佳答案

这是一个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'))

关于用于解析 block 的 Python 实用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30112200/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com