在pyyam中使用键/值继承,但将其保留在结果之外

2024-04-25 14:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

PyYAML对于键/值对的继承非常酷,但是在最终的结构中不包括下面的base\u value\u结构是可能的。你知道吗

Default_profile: &Default_profile
    base_value_structure: &base_value_structure
        path_to_value: 'path to element'
        selector_type: 'XPATH'
        required: false
    title:
        <<: *base_value_structure
        path_to_value: "//div[@id='ctitle']/text()"

解析完上面的配置之后,结果中就出现了基值结构。我可以阻止这种行为还是需要手动过滤?你知道吗

期望结果:

{"Default_profile": {
    "title": {
        "path_to_value": "//div[@id='ctitle']/text()",
        "selector_type": "XPATH",
        "required": False }
     }
}

Tags: topathdividdefaultbasetitlevalue
1条回答
网友
1楼 · 发布于 2024-04-25 14:35:01

你需要用手把它过滤掉。在合并键的specification中没有规定。你知道吗

如果不将映射作为Python dict加载,而是作为更复杂的类型加载,则可以自动过滤这些“基本”映射,但代价是使YAML文件的语法复杂化。你知道吗

还可以调整解析器以保留用作基的映射列表,并删除所使用的映射列表。或者,如果只有“基”映射有锚点,则只删除那些。这些都不能用PyYAML来完成。你知道吗

但是,锚定映射不必与键具有相同的锚定名称。锚定映射根本不必是键值(在您的示例中就是这样)。通过对YAML文件重新排序,您可以更轻松地删除“基”甚至多个基:

from pprint import pprint
import ruamel.yaml as yaml

yaml_str = """\
-
  - &base_value_structure
    path_to_value: 'path to element'
    selector_type: 'XPATH'
    required: false
  - &base_other_structure
    key1: val1
    key2: val2
- Default_profile: &Default_profile
    title:
        <<: *base_value_structure
        path_to_value: "//div[@id='ctitle']/text()"
"""

data = yaml.load(yaml_str)[1]
pprint(data)

提供:

{'Default_profile': {'title': {'path_to_value': "//div[@id='ctitle']/text()",
                               'required': False,
                              'selector_type': 'XPATH'}}}

在上面的例子中,我使用了我的ruamel.yaml库,它是PyYAML的一个派生,在本例中,它的工作原理应该与PyYAML相同,但是如果使用它的往返加载程序/转储程序,它将保留合并信息。你知道吗

相关问题 更多 >