如何将 yaml 文件读入 Jupyter 笔记本?

时间:2021-02-26 04:41:37

标签: python import jupyter-notebook yaml jupyter

我有一个来自 Open API 规范的文件,我一直试图在 Jupyter 笔记本中访问该文件。它是一个 .yaml 文件。我能够将它上传到 Jupyter 并将它放在与我想用来访问它的笔记本相同的文件夹中。我是 Jupyter 和 Python 的新手,所以如果这是一个基本问题,我很抱歉。我找到了一个论坛,建议使用此代码读取数据(在我的文件中:“openapi.yaml”):

import yaml

with open("openapi.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

这似乎将数据引入,但它是一个完全非结构化的流,如下所示:

{'openapi': '3.0.0', 'info': {'title': 'XY Tracking API', 'version': '2.0', 'contact': {'name': 'Narrativa', 'url': 'http://link, 'email': '}, 'description': 'The XY Tracking Project collects information from different data sources to provide comprehensive data for the XYs, X-Y. Contact Support:'}, 'servers': [{'url': 'link'}], 'paths': {'/api': {'get': {'summary': 'Data by date range', 'tags': [], 'responses': {'200': {'description': 'OK', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/covidtata'}}}}}, 'operationId': 'get-api', 'parameters': [{'schema': {'type': 'string', 'format': 'date'}, 'in': 'query', 'name': 'date_from', 'description': 'Date range beginig (YYYY-DD-MM)', 'required': True}, {'schema': {'type': 'string', 'format': 'date'}, 'in': 'query', 'name': 'date_to', 'description': 'Date range ending (YYYY-DD-MM)'}], 'description': 'Returns the data for a specific date range.'}}, '/api/{date}': {'parameters': [{'schema': {'type': 'string', 'format': 'date'}, 'name': 'date', 'in': 'path', 'required': True}], 'get': {'summary': 'Data by date', 'tags': [], 'responses': {'200': {'description': 'OK', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/data'}}}}}, 'operationId': 'get-api-date', 'description': 'Returns the data for a specific day.'}}, '/api/country/{country}': {'parameters': [{'schema': {'type': 'string', 'example': 'spain'}, 'name': 'country', 'in': 'path', 'required': True, 'example': 'spain'}, {'schema': {'type': 'strin

...etc.

我想通过数据进行分析,但似乎无法正确访问它。任何帮助将不胜感激!!!非常感谢您的阅读。

1 个答案:

答案 0 :(得分:1)

您在输出中看到的是 JSON。这是一种机器可读的格式,不需要人类可读的换行符或缩进。您应该能够在代码中很好地处理这些数据。

或者,您可能需要考虑另一个解析器/发射器,例如 ruamel.yaml,它可以比您当前导入的包更容易处理 YAML 文件。使用此包打印语句可以保留行和缩进以提高可读性。