gpt4 book ai didi

python - 如何从 yaml 文件中删除文本 "!!omap"?

转载 作者:行者123 更新时间:2023-12-04 07:30:06 25 4
gpt4 key购买 nike

我试图从 YAML 文件中删除几个属性,我成功地这样做了,但它在输出文件中有一些额外的字符,不知道如何删除这些。
这是输入的 YAML 文件:

Person:
Name: John
Children:
- Stacy
- Rick
- Josh
Wife:
Name: Mary
Id: 123
在删除几个属性后,我期待 YAML 文件如下:
Person: 
Name: John
Children:
- Rick
- Stacy
这是我正在使用的脚本:
import re
import time
from collections import OrderedDict

from ruamel.yaml import ruamel

file_path = '/path/to/yml/file'
# Read yaml file
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_path))

allowed_attributes = ['Name', 'Children']
allowed_children = ['Rick', 'Stacy']

root_node_name = 'Person'

config[root_node_name] = OrderedDict((attribute_name, config[root_node_name][attribute_name]) for attribute_name in allowed_attributes)
config[root_node_name]['Children'] = [child_name for child_name in allowed_children]


new_file_path = f"{re.sub('.yml','',file_path)}_{time.strftime('%Y%m%d-%H%M%S')}.yml"

with open(new_file_path, "w") as fp:
ruamel.yaml.YAML().dump(config, fp)
这是它生成的文件:
Person: !!omap
- Name: John
- Children:
- Rick
- Stacy
  • 如何删除 !!omap第一行的文字?
  • 如何删除 - (破折号)在 Name 旁边和 Children ?

  • 我知道在文件中包含这些字符不会影响功能,但我很好奇如何删除输入文件中不存在的那些字符。
    我正在使用 Python3 和 ruamel.yaml 版本是 0.17.4

    最佳答案

    在 YAML 映射中定义为无序,当然键在 YAML 文档中有明确的顺序。
    因此,如果您转储显式排序的映射,例如 Python 的 OrderedDict有保证的订购是通过倾销
    单个映射的序列(总是有序的),标记为 !!omap .如果你会读回输出,你会再次
    得到一个 OrderedDict使用时 ruamel.yaml ,正如您已经注意到的那样,没有任何问题(但一些处理链中输出的工具可能无法正确处理)。
    较新的 Python 3 实现中的字典是有序的,并且将在没有此类标签且没有所需序列的情况下转储
    以保证订单。使用 CommentedMap 可以实现 Python 2.7+ 的相同效果。 ,它充当 OrderedDict(不转储标签):

    import sys

    import ruamel.yaml
    from ruamel.yaml.comments import CommentedMap as OrderedDict

    file_path = 'input.yaml'
    config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_path))
    yaml = ruamel.yaml.YAML()
    yaml.indent(sequence=ind, offset=bsi) # set the original sequence indent and offset of the dash

    allowed_attributes = ['Name', 'Children']
    allowed_children = ['Rick', 'Stacy']

    root_node_name = 'Person'

    config[root_node_name] = OrderedDict((attribute_name, config[root_node_name][attribute_name]) for attribute_name in allowed_attributes)
    config[root_node_name]['Children'] = [child_name for child_name in allowed_children]


    yaml.dump(config, sys.stdout)
    这使:
    Person:
    Name: John
    Children:
    - Rick
    - Stacy
    请注意,包含 YAML 文档的文件的官方推荐扩展名是 .yaml自 2007 年以来。
    更令人困惑的是,还有一种更古老但不常遇到的 YML 格式,它是 XML 的派生形式。
    因此,请考虑更新您的扩展程序和代码。

    关于python - 如何从 yaml 文件中删除文本 "!!omap"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67994516/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com