【问题标题】:How to convert dot separated string into yaml format using python script如何使用python脚本将点分隔字符串转换为yaml格式
【发布时间】:2020-01-06 13:38:13
【问题描述】:

我的文件有一些属性 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

【问题讨论】:

  • that 可能会对您有所帮助,也可以查看this 以获得更精致的版本。
  • 你怎么知道在cd之间必须有一个序列,而不是在bc之间?如果您的输入是 a.b.c.0.da.b.c.0.e 等,那会很明显,但事实并非如此。

标签: python python-3.x pyyaml ruamel.yaml


【解决方案1】:

使用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'

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2018-03-22
    • 2014-05-24
    • 2013-03-28
    相关资源
    最近更新 更多