需要一个从 yaml 文件中提取内容并输出为 csv 文件的脚本

2024-05-24

我对 python 很陌生,但我很感激您帮助指导我创建一个简单的脚本,该脚本读取一堆 .yaml 文件(同一目录中的大约 300 个文件)并从.yaml 文件并将其转换为 csv。

.yaml 文件中内容的示例

code: 9313
degrees:
- name: Design
  coreCourses:
  - ABCD1
  - ABCD2
  - ABCD3
  electiveGroups: #this is the section i need to extract
    - label: Electives
      options:
        - Studio1
        - Studio2
        - Studio3
    - label: OtherElectives
      options:
        - Class1
        - Development2
        - lateclass1
   specialisations:
    - label: Honours

我希望如何查看 csv 中的输出:

.yaml file name | Electives   | Studio1
.yaml file name | Electives   | Studio2
.yaml file name | Electives   | Studio3
.yaml file name | OtherElectives   | class1
.yaml file name | OtherElectives   | Development2
.yaml file name | OtherElectives   | lateclass1

我假设这将是一个相对简单的脚本 - 但我正在寻找一些帮助来编写它。我对此很陌生,所以请耐心等待。我已经编写了一些 vba 宏,所以我希望我能相对较快地掌握。

最好的是一个完整的解决方案,并提供一些有关代码如何工作的指导。

提前感谢您的所有帮助。我希望我的问题很清楚

这是我的第一次尝试(尽管花费的时间不长):

import yaml
with open ('program_4803','r') as f:
    doc = yaml.load(f)
    txt=doc["electiveGroups"]["options"]
    file = open(“test.txt”,”w”) 
        file.write(“txt”) 
        file.close()

正如您可能知道的那样,目前这还非常不完整 - 但我正在尽最大努力!


这可能有帮助:

import yaml
import csv

yaml_file_names = ['data.yaml', 'data2.yaml']


rows_to_write = []

for idx, each_yaml_file in enumerate(yaml_file_names):
    print("Processing file ", idx+1, "of", len(yaml_file_names), "file name:", each_yaml_file)
    with open(each_yaml_file) as f:
        data = yaml.load(f)

        for each_dict in data['degrees']:
            for each_nested_dict in each_dict['electiveGroups']:
                for each_option in each_nested_dict['options']:
                    # write to csv yaml_file_name, each_nested_dict['label'], each_option
                    rows_to_write.append([each_yaml_file, each_nested_dict['label'], each_option])



with open('output_csv_file.csv', 'w') as out:
    csv_writer = csv.writer(out, delimiter='|')
    csv_writer.writerows(rows_to_write)
    print("Output file output_csv_file.csv created")

使用两个模拟输入 yaml 测试了此代码data.yaml and data2.yaml,其内容如下:

data.yaml:

code: 9313
degrees:
- name: Design
  coreCourses:
  - ABCD1
  - ABCD2
  - ABCD3
  electiveGroups: #this is the section i need to extract
    - label: Electives
      options:
        - Studio1
        - Studio2
        - Studio3
    - label: OtherElectives
      options:
        - Class1
        - Development2
        - lateclass1
  specialisations:
  - label: Honours

and data2.yaml:

code: 9313
degrees:
- name: Design
  coreCourses:
  - ABCD1
  - ABCD2
  - ABCD3
  electiveGroups: #this is the section i need to extract
    - label: Electives
      options:
        - Studio1
    - label: E2
      options:
        - Class1
  specialisations:
  - label: Honours

生成的输出 csv 文件是这样的:

data.yaml|Electives|Studio1
data.yaml|Electives|Studio2
data.yaml|Electives|Studio3
data.yaml|OtherElectives|Class1
data.yaml|OtherElectives|Development2
data.yaml|OtherElectives|lateclass1
data2.yaml|Electives|Studio1
data2.yaml|E2|Class1

顺便说一句,您随问题一起提供的 yaml 输入,最后两行没有正确缩进

正如你所说,你需要解析一个目录中的 300 个 yaml 文件,那么,你可以使用globpython 的模块,如下所示:

import yaml
import csv
import glob


yaml_file_names = glob.glob('./*.yaml')
# yaml_file_names = ['data.yaml', 'data2.yaml']

rows_to_write = []

for idx, each_yaml_file in enumerate(yaml_file_names):
    print("Processing file ", idx+1, "of", len(yaml_file_names), "file name:", each_yaml_file)
    with open(each_yaml_file) as f:
        data = yaml.load(f)

        for each_dict in data['degrees']:
            for each_nested_dict in each_dict['electiveGroups']:
                for each_option in each_nested_dict['options']:
                    # write to csv yaml_file_name, each_nested_dict['label'], each_option
                    rows_to_write.append([each_yaml_file, each_nested_dict['label'], each_option])



with open('output_csv_file.csv', 'w') as out:
    csv_writer = csv.writer(out, delimiter='|', quotechar=' ')
    csv_writer.writerows(rows_to_write)
    print("Output file output_csv_file.csv created")

Edit:正如您在评论中要求跳过那些yaml没有的文件electiveGroup部分,这是更新的程序:

import yaml
import csv
import glob


yaml_file_names = glob.glob('./*.yaml')
# yaml_file_names = ['data.yaml', 'data2.yaml']

rows_to_write = []

for idx, each_yaml_file in enumerate(yaml_file_names):
    print("Processing file ", idx+1, "of", len(yaml_file_names), "file name:", each_yaml_file)
    with open(each_yaml_file) as f:
        data = yaml.load(f)

        for each_dict in data['degrees']:
            try:
                for each_nested_dict in each_dict['electiveGroups']:
                    for each_option in each_nested_dict['options']:
                        # write to csv yaml_file_name, each_nested_dict['label'], each_option
                        rows_to_write.append([each_yaml_file, each_nested_dict['label'], each_option])
            except KeyError:
                print("No electiveGroups or options key found in", each_yaml_file)


with open('output_csv_file.csv', 'w') as out:
    csv_writer = csv.writer(out, delimiter='|', quotechar=' ')
    csv_writer.writerows(rows_to_write)
    print("Output file output_csv_file.csv created")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

需要一个从 yaml 文件中提取内容并输出为 csv 文件的脚本 的相关文章

随机推荐

  • 在 UIAlertController 的文本字段中选择文本

    我需要在 UIAlertController 出现后立即选择文本字段的文本 但是 我在标准 UITextField 中选择文本的方式在这里不起作用 这就是我尝试过的 但我似乎无法让它发挥作用 let ac UIAlertController
  • D3.js - 更改鼠标悬停时元素的不透明度 IF 条件 = false

    我正在制作一个带有过滤器的交互式 D3 js 图表 当用户单击选定的复选框时 该过滤器会显示点 此外 在鼠标悬停事件上 所选点旁边将出现一个弹出窗口 其中包含一些信息 由于图表上的点数量相对较多 因此我选择在取消选中相应复选框时使相关点变得
  • cellForRowAtIndexPath:未调用

    我的应用程序有两种状态 已登录和未登录 并且我有以下架构 大大简化 ViewController A 包含一个搜索框和一个表视图 ViewController B 用于登录应用程序 流程如下 用户未登录 A 被压入堆栈 在viewWillA
  • 连接到没有元数据的网络服务

    我想连接到此网络服务 https training api temando com schema 2009 06 server wsdl https training api temando com schema 2009 06 serve
  • Android 2.2 中不带预览的相机捕获

    我需要捕获图像而不显示预览 我想在后台作为服务来完成它 可以这样做吗 是有可能实现的 您应该定义一个处理 Camera 对象的类 例如调用 Camera open 等 不要为相机对象提供以下行以禁用预览 mCamera setPreview
  • 如何检测应用程序正在运行的 .NET 版本?

    我尝试使用Environment Version ToString 确定目标计算机上正在使用什么 NET 框架 但安装了 4 0 版本时 它说我正在使用 NET 2 0 如何检测目标计算机上正在运行的 NET Framework 版本 En
  • 如何让 STDOUT 和 STDERR 都转到终端和日志文件?

    我有一个脚本 将由非技术用户交互式运行 该脚本将状态更新写入 STDOUT 以便用户可以确定脚本运行正常 我希望将Stdout和STDERR重定向到终端 以便用户可以看到脚本正在工作 并查看是否存在问题 我还希望将两个流都重定向到日志文件
  • 更新实时智能合约

    如果我有一个智能合约 其中硬编码了一些其他智能合约的地址 例如 也许我的合约有一些外部流动性挖矿金库的地址 它会定期存入一些余额 现在假设我想更新该地址列表并迁移它而不扰乱当前合约的操作 最好的方法是什么 以太坊字节码是不可变的 所以简单的
  • 本地提交推送到中央服务器

    在工作中 我们使用 perforce 并被鼓励定期对其进行承诺 我对此很满意 然而 我想运行像 Mercurial 这样的东西 这样我就可以在本地提交正在进行的工作并且不一定编译 运行的东西 然后从中定期提交到中央 perforce 服务器
  • Matplotlib 渲染日期、图像的问题

    我在使用 conda forge 的 Matplotlib v 3 1 3 和 python 3 7 时遇到问题 我拥有 Matplotlib 所需的所有依赖项 当我输入这段代码时 它应该可以工作 我得到了泼溅艺术 它基于此 YouTube
  • 无法从 HBase 导出表

    我无法将表从 HBase 导出到 HDFS 下面是错误跟踪 它的尺寸相当大 还有其他方法可以导出吗 我使用下面的命令来导出 我增加了 rpc 超时但作业仍然失败 sudo u hdfs hbase Dhbase rpc timeout 10
  • 如何在JasperReport中插入分页符

    我有一个 JasperReports 模板 带有填充的细节带 如果我运行该报告 我的页数为 27 27 个详细信息行 我希望详细信息行号 12 以新页面开始 因此我必须在页数 11 之后插入分页符 但我找不到 pagebreak 元素 它在
  • WebCore::UserGestureIndicator::processingUserGesture 中的 EXC_BAD_ACCESS (SIGSEGV)

    我有一个使用 UIWebView 和 HTML5 websockets 构建的 iOS 应用程序 该应用程序经历了看似随机的崩溃 它发生在用户与其交互时以及在用户和应用程序之间没有发生交互的寿命测试期间 崩溃日志都有以下内容 Excepti
  • 如何有效地计算另一列中每个元素的较大元素的数量?

    我有以下内容df name created utc 0 t1 cqug90j 1430438400 1 t1 cqug90k 1430438400 2 t1 cqug90z 1430438400 3 t1 cqug91c 143043840
  • 如何将登录哈希 bcrypt 更改为 hash256

    我正在尝试更改 Laravel 中的哈希值 所以我在 RegisterController 中使用 salt 定制了 SHA256 注册完成但如何更改登录信息 protected function create array data sal
  • PostgreSQL 强制使用小写名称?

    刚刚开始通过C和libpq在linux上学习PostgreSQL 9 1 现在我检查连接 连接 创建数据库 创建表和其他基本内容 但我注意到在创建表期间 PQ 将我的数据库名称转换为小写 然后我看到表名和字段名也被强制小写 但是 当我尝试连
  • 如何隐藏或删除 Android HoneyComb 中的状态栏?

    如何隐藏或删除 Android HoneyComb 中的状态栏 每次运行应用程序时 我都会发现某些内容必须被状态栏覆盖 我尝试改变AndroidManifest xml 但没有任何改变 你不知道 它被认为是永久的屏幕装饰 就像电容式主页 菜
  • 在 Android Studio 中打开上次关闭的选项卡

    我是 Android Studio 的新手 想知道是否有任何快捷方式 选项可以重新打开上次关闭的选项卡 没有分配快捷方式 但您可以轻松分配新的快捷方式 Go to IDE settings Keymap Main menu Window E
  • 如何运行 Mike Bostock 的 D3 示例?

    我一直在尝试经营迈克博斯托克透视地球仪 http bl ocks org mbostock 6747043例如 但是如果您尝试在本地重现它 则对其 json 文件的引用是不正确的 问题来自于这行代码 d3 json mbostock raw
  • 需要一个从 yaml 文件中提取内容并输出为 csv 文件的脚本

    我对 python 很陌生 但我很感激您帮助指导我创建一个简单的脚本 该脚本读取一堆 yaml 文件 同一目录中的大约 300 个文件 并从 yaml 文件并将其转换为 csv yaml 文件中内容的示例 code 9313 degrees