英文:
How to convert dot separated string into yaml format using python script
问题
我想将这个文件转换成YAML格式,所期望的输出应该是:
a:
b:
c:
- d: '0'
e: hello
f: hello1
g:
- h: '123'
i: '4567'
http_port: false
install_java: true
英文:
I am having a file having some properties 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
I want to dump this file into yaml format, so the expected output should be:
a:
b:
c:
- d: '0'
e: hello
f: hello1
g:
- h: '123'
i: '4567'
http_port : false
install_java : true
答案1
得分: 4
使用这个递归函数,你可以将你的dotmap字符串转换为一个字典,然后执行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"""
# 从dotmap字符串创建一个字典:
d = {}
for substring in dotmap_string.split('\n'):
kv = substring.split(' : ')
d = add_branch(d, kv[0].split('.'), kv[1])
# 现在将字典转换为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'
英文:
using this nice recursive function, you could convert your dotmap string to a dict and then do a 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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论