【问题标题】:Parsing a yaml file using PyYaml?使用 PyYaml 解析 yaml 文件?
【发布时间】:2021-05-17 08:58:14
【问题描述】:

我有一个 .yaml 文件,里面有以下格式:

  ament_tools:
    release:
      tags:
        release: release/ardent/{package}/{version}
      url: https://github.com/ros2-gbp/ament_tools-release.git
      version: 0.4.0-0
    source:
      type: git
      url: https://github.com/ament/ament_tools.git
      version: ardent
    status: maintained
  cartographer:
    release:
      tags:
        release: release/ardent/{package}/{version}
      url: https://github.com/ros2-gbp/cartographer-release.git
      version: 2.0.0-1
    source:
      type: git
      url: https://github.com/ros2/cartographer.git
      version: ardent
    status: maintained

我想检索source 中的url 信息。到目前为止,上面的示例,我想检索https://github.com/ament/ament_tools.githttps://github.com/ros2/cartographer.git URL。

我在下面写了一些代码,但本质上,我想将上面列出的 URL 添加到我已初始化的 urls 列表中。我该如何具体解析source,然后解析url

def get_urls(distribution):
    urls = list()
    tag1 = "source"
    tag2 = "url"
    
    # Open distribution.yaml file and collect urls in list
    for file in os.listdir("distribution/"):
        if file.startswith(distribution):
            dist_file = "distribution/" + file
            stream = open(dist_file, 'r')
            data = yaml.load(stream)
            

    print(urls)
    return urls

【问题讨论】:

    标签: python parsing search yaml pyyaml


    【解决方案1】:

    我更新了 get_urls() 以根据请求返回 URL 列表,否则返回 None。 我希望我能帮上忙。

    def get_urls(distribution):
        urls = list()
        tag1 = "source"
        tag2 = "url"
        result_list = []
        # Open distribution.yaml file and collect urls in list
        try:
            for file in os.listdir("distribution/"):
                if file.startswith(distribution):
                    dist_file = "distribution/" + file
                    stream = open(dist_file, 'r')
                    data = yaml.safe_load(stream)
        except:
            pass
        for elt in data:
            result_list.append(data[elt]['source']['url'])
        return result_list
        return None
    

    输出:

    ['https://github.com/ament/ament_tools.git', 'https://github.com/ros2/cartographer.git']
    

    【讨论】:

      【解决方案2】:

      yaml.load(stream) 将读取整个文件并将其存储为 python 数据结构。然后,您可以使用列表或字典操作来检索 url。本质上,您可以分别通过索引或键访问。

      【讨论】:

        猜你喜欢
        • 2012-07-20
        • 2021-04-01
        • 2019-02-13
        • 2016-09-12
        • 2020-07-22
        • 1970-01-01
        • 2020-01-16
        • 2020-10-14
        • 2020-07-18
        相关资源
        最近更新 更多