【问题标题】:How to remove text "!!omap" from yaml file?如何从 yaml 文件中删除文本“!!omap”?
【发布时间】:2021-08-31 19:00:39
【问题描述】:

我正在尝试从 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
  1. 如何删除第一行的!!omap 文本?
  2. 如何删除NameChildren 旁边的-(破折号)?

我知道文件中包含这些字符不会影响功能,但我很好奇如何删除输入文件中不存在的那些字符。

我使用的是 Python3,ruamel.yaml 版本是 0.17.4

【问题讨论】:

  • 我来自荷兰,我读到你的名字是 J.A.范 Oob %-)

标签: python python-3.x yaml ruamel.yaml


【解决方案1】:

在 YAML 中,映射被定义为无序,当然键在 YAML 文档中具有明确的顺序。 因此,如果您转储显式排序的映射,例如 Python 的 OrderedDict,则保证排序是通过转储 单个映射的序列(总是有序的),标记为!!omap。如果您要读回该输出,您将再次 使用ruamel.yaml 时获得OrderedDict,因此您已经注意到没有任何问题(但是一些处理输出链的工具可能无法正确处理此问题)。

较新的 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

请注意,自 2007 年以来,官方推荐的包含 YAML 文档的文件的扩展名是 .yaml。 更令人困惑的是,还有一种更古老但不经常遇到的 YML 格式,它是 XML 的衍生格式。 所以请考虑更新你的扩展和代码。

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2018-07-21
    • 2013-02-18
    • 2020-10-15
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多