Python yaml.dump 将标量值的单引号更改为双引号

问题描述 投票:0回答:1

我通过使用模块“pyyaml”的

yaml.dump
函数在 Python 中转储字典来生成 YAML 文件。以下是我的代码,它将字典转储到 YAML 文件中。

with open('test.yaml', 'w') as outfile:
    yaml.dump(yaml_dict, outfile, default_flow_style=False, sort_keys=False)

上面的脚本创建一个 YAML 文件,该文件表示带有单引号的标量值(例如“5”),如下所示

data:
- name: Name
  value: John
- name: Age
  value: '5'

但是,我希望 YAML 文件用双引号表示标量值。所需输出:

data:
- name: Name
  value: John
- name: Age
  value: "5"

如何以标量值用双引号表示的方式将字典传递到 YAML 文件?

python yaml
1个回答
0
投票

如果你想为字典的字符串添加双引号,你可以做的一个技巧是覆盖

https://github.com/yaml/pyyaml/blob/main/lib/yaml/representer.py
中的 represent_mapping并添加字符串的特殊情况。例如:

import yaml

import logging
import yaml
from yaml.nodes import ScalarNode, MappingNode, SequenceNode


class DoubleQuotesDumper(yaml.Dumper):

    def represent_sequence(self, tag, sequence, flow_style=None):
        value = []
        node = SequenceNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        for item in sequence:
            node_item = self.represent_data(item)

            # This is the trick to make double quotes, the rest
            # a is taken from https://github.com/yaml/pyyaml/blob/main/lib/yaml/representer.py
            if isinstance(item, str):
                node_item.style = '"'
            # end of trick

            if not (isinstance(node_item, ScalarNode) and not node_item.style):
                best_style = False
            value.append(node_item)
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def represent_mapping(self, tag, mapping, flow_style=None):
        value = []
        node = MappingNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        if hasattr(mapping, "items"):
            mapping = list(mapping.items())
            if self.sort_keys:
                try:
                    mapping = sorted(mapping)
                except TypeError:
                    pass
        for item_key, item_value in mapping:
            node_key = self.represent_data(item_key)
            node_value = self.represent_data(item_value)

            # This is the trick to make double quotes, the rest
            # a is taken from https://github.com/yaml/pyyaml/blob/main/lib/yaml/representer.py
            if isinstance(item_value, str):
                node_value.style = '"'
            # end of trick

            if not (isinstance(node_key, ScalarNode) and not node_key.style):
                best_style = False
            if not (isinstance(node_value, ScalarNode) and not node_value.style):
                best_style = False
            value.append((node_key, node_value))
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node


a = {
    "key1": "value1",
    "key2": 2,
    "key3": {"internalkey1": ["internalvalue1", 111111], "internalkey2": 22222222},
}

print(yaml.dump(a, Dumper=DoubleQuotesDumper, default_flow_style=False))
print(yaml.dump(a, default_flow_style=False))

此代码覆盖了 python 中字符串列表和字典的转储,因此默认为:

key1: value1
key2: 2
key3:
  internalkey1:
  - internalvalue1
  - 111111
  internalkey2: 22222222

它将打印

key1: "value1"
key2: 2
key3:
  internalkey1:
  - "internalvalue1"
  - 111111
  internalkey2: 22222222

相反。

© www.soinside.com 2019 - 2024. All rights reserved.