python - 如何使用 chomping 指示器在 PyYaml 中添加文字字符串模式 |-

标签 python pyyaml

我正在尝试从 Python 对象生成一个 YAML 文件,其中我有一些文字字符串属性 pattern = "^[0-9]+$" 以添加到同名节点 pattern 作为文件夹 block 。

代码

到目前为止我已经进步到下面的代码

import yaml
class MyDumper(yaml.Dumper):
    def increase_indent(self, flow=False, indentless=False):
        return super(MyDumper, self).increase_indent(flow, False)


source = {'row_filters':{'NONE':{'filter_sql_expr': True}},
          'rule_dimensions': ['completeness','conformance'],
          'rules': {'VALID_CUSTOMER_ID': {'rule_type': 'REGEX', 'dimension': 'accuracy', 'params': {'pattern': "^[0-9]+$"}}}}    

print(yaml.dump(source, Dumper=MyDumper, default_flow_style=False,sort_keys=False,indent=2,allow_unicode=True))

实际 YAML 输出

row_filters:
  NONE:
    filter_sql_expr: True
rule_dimensions:
  - completeness
  - conformance
rules:
  VALID_CUSTOMER_ID:
    rule_type: REGEX
    dimension: accuracy
    params:
      pattern: ^[0-9]+$

预期的 YAML 输出

row_filters:
 NONE:
   filter_sql_expr: |-
      True
rule_dimensions:
  - completeness
  - conformance
rules:
  VALID_CUSTOMER_ID:
    rule_type: REGEX
    dimension: accuracy
    params:
      pattern: |-
        ^[0-9]+$

想要

我需要为带有 block chomping indicator 的多行 block 添加 |- - 为了将字符串添加为 block 文字。

问题

  1. 如何使用 |- 强制添加 block 样式的字符串?
  2. 如何将方法添加到我的 Dumper 类中进行转换?

最佳答案

您可以使用Representer.add_representer() 来显示 block 文字,更多细节here

class folded_str(str): pass

class literal_str(str): pass

class literal_unicode(str): pass

def change_style(style, representer):
    def new_representer(dumper, data):
        scalar = representer(dumper, data)
        scalar.style = style
        return scalar
    return new_representer

import yaml
from yaml.representer import SafeRepresenter

yaml.add_representer(literal_str, represent_literal_str)

fse = True
ptrn = "^[0-9]+$"

source = {'row_filters':{'NONE':{'filter_sql_expr': literal_str(fse)}},
          'rule_dimensions': ['completeness','conformance'],
          'rules': {'VALID_CUSTOMER_ID': {'rule_type': 'REGEX', 'dimension': 'accuracy', 'params': {'pattern':literal_str(ptrn)}}}}

print(yaml.dump(source))

输出

row_filters:
  NONE:
    filter_sql_expr: |-
      True
rule_dimensions:
- completeness
- conformance
rules:
  VALID_CUSTOMER_ID:
    dimension: accuracy
    params:
      pattern: |-
        ^[0-9]+$
    rule_type: REGEX

关于python - 如何使用 chomping 指示器在 PyYaml 中添加文字字符串模式 |-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74955147/

相关文章:

python - 在 PyQt5 中显示和隐藏多个窗口

python - 无法将简单的python代码转换为haskell

python - 如何将 yaml.load_all 与 fileinput.input 一起使用?

yaml - 指定 PyYAML 转储部分的样式

python - 在 PyYAML 中格式化自定义类输出

python - 使用输入文件对象从python中的文件中读取变量

python - 使用 np.random 生成值

Python - 如果在类中使用了未声明的变量,则强制出错

python - 编辑现有的 yaml 文件但保留原始注释

python - YAML 中映射的映射中的文字