如何使用python脚本将点分隔的字符串转换为yaml格式

问题描述 投票:-2回答:1

我有一个具有某些属性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
python python-3.x pyyaml ruamel.yaml
1个回答
0
投票

使用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'
© www.soinside.com 2019 - 2024. All rights reserved.