将 YAML 转换为 Python 中的字符串

问题描述 投票:0回答:2

我正在尝试将 yaml 文件转换为特定格式。 YAML 文件如下所示:

treeroot:
    branch1:
        name: 1
        branch1-1:
            name: 2
    branch2:
        name: 3
        branch2-1:
            name: 4

我想将上述文件作为输入并按以下格式打印输出:

system.treeroot.branch1.name 1
system.treeroot.branch1.branch1-1.name 2
system.treeroot.branch2.name 3
system.treeroot.branch2.branch2-1.name 4

这是我写的代码:

#!/usr/bin/python

import yaml
m = "system"
def main():
    yaml_data = yaml.load(open('test.yaml'))
    recurse(yaml_data)

def recurse(yaml_data):
    for k,v in yaml_data.iteritems():
        global m
        if type(v) == type({}):
            m = m + "." + k
            recurse(v)
        else:
            m = m + "." + k
            print str(m)+" "+str(v)

if __name__ == "__main__":
    main()

但是这段代码打印的输出是这样的:

system.treeroot.branch2.branch2-1.name 4
system.treeroot.branch2.branch2-1.name.name 3
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name 2
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name.name 1

我该如何解决这个问题?

python yaml
2个回答
1
投票

首先,关于风格的说明,最好使用

isinstance
而不是直接比较类型,即
if isinstance(v, dict):

如果你让你的函数接受两个参数而不是试图摆弄全局

m
,你应该解决你的问题。

def recurse(yaml_data, m):
    for k,v in yaml_data.iteritems():
        if isinstance(v, dict):
            # m = m + "." + k
            recurse(v, m + "." + k)
        else:
            m = m + "." + k
            print str(m)+ " " +str(v)

# In [4]: recurse(yaml_data, 'system')
# system.treeroot.branch2.branch2-1.name 4
# system.treeroot.branch2.name 3
# system.treeroot.branch1.branch1-1.name 2
# system.treeroot.branch1.name 1

0
投票

pip install pyyaml

import yaml
data_dict = { 'a': "some data", b: ['ponit 1', 'point 2'] }
yaml_str = yaml.dump(data_dict)
print(yaml_str)

# or to write it in a file
with open('filename.yaml', 'w') as file:
    yaml.dump(data_dict, file)
© www.soinside.com 2019 - 2024. All rights reserved.