python和yaml提取某些yaml字段的值

时间:2018-08-09 10:38:06

标签: python dictionary

我有以下情况:

一个Yaml文件:

team:
  owner: 
  contact:
  channel:
  role:
    role1: 3r
    role2: 6q

还有一个Python脚本,需要提取role:的键值对

def yaml_processor(role):
    filepath = "../1/2/3.yaml"
    data = yaml_loader(filepath)
    data = data.get(role)
    for team in data.iteritems():
        print(role)
    file.close()

1 个答案:

答案 0 :(得分:2)

您的代码中有些奇怪的地方,但让我们开始 定义yaml_loader

from ruamel.yaml import YAML

def yaml_loader(file_path):
   yaml = YAML()
   with open(file_path) as fp:
      data = yaml.load(fp)
   return data

将YAML加载到分层数据结构中。在根 该结构是一个dict,只有一个键:team,因为在根 文档中有一个带有该键的映射。

关于您的代码:

  • 您始终为每个团队将参数打印到yaml_processor 找。您没有使用YAML文档中的数据
  • 您尝试将YAML文档中获取的数据替换为 data.get(role),仅在role == 'team'时有效,因为 在根级别只有一个键
  • 您做file.close()是什么file
  • 您正在使用.iteritems(),它是Python 2的构造。 Python 2 是end-of-life in 2020。你真的 是否打算在游戏后期学习使用Python 2特定代码?

我将包括:

from future import print_function

在我的程序顶部,然后执行以下操作:

def yaml_processor():
    # filepath = "../1/2/3.yaml"
    filepath = '3.yaml'  # different filestructure on my disc
    data = yaml_loader(filepath)
    for team in data:
        team_data = data[team]
        for role_nr in team_data['role']:
            role = team_data['role'][role_nr]
            print('team {}, role number: {}, role: {}'.format(team, role_nr, role))

yaml_processor()

给出:

team team, role number: role1, role: 3r
team team, role number: role2, role: 6q

如果您不太确定要使用键role1role2,则应该 考虑在您的YAML文档中使用序列:

team:
  owner: 
  contact:
  channel:
  roles:
    - 3r
    - 6q
相关问题