如何使用Python脚本将点分隔的字符串转换为YAML格式。

huangapple go评论77阅读模式
英文:

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'

huangapple
  • 本文由 发表于 2020年1月6日 21:38:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定