我有一个具有某些属性myprop.properties的文件
a.b.c.d : '0'
a.b.c.e : 'hello'
a.b.c.f : 'hello1'
a.b.g.h : '123'
a.b.g.i : '4567'
http_port : false
install_java : true
我想将此文件转储为Yaml格式,所以预期的输出应为:
a:
b:
c:
- d: '0'
e: hello
f: hello1
g:
- h: '123'
i: '4567'
http_port : false
install_java : true
使用this不错的递归函数,您可以将点图字符串转换为字典,然后执行yaml.dump
:
def add_branch(tree, vector, value):
key = vector[0]
if len(vector) == 1:
tree[key] = value
else:
tree[key] = add_branch(tree[key] if key in tree else {}, vector[1:], value)
return tree
dotmap_string = """a.b.c.d : '0'
a.b.c.e : 'hello'
a.b.c.f : 'hello1'
a.b.g.h : '123'
a.b.g.i : '4567'
http_port : false
install_java : true"""
# create a dict from the dotmap string:
d = {}
for substring in dotmap_string.split('\n'):
kv = substring.split(' : ')
d = add_branch(d, kv[0].split('.'), kv[1])
# now convert the dict to YAML:
import yaml
print(yaml.dump(d))
# a:
# b:
# c:
# d: '''0'''
# e: '''hello'''
# f: '''hello1'''
# g:
# h: '''123'''
# i: '''4567'''
# http_port: 'false'
# install_java: 'true'