我正在尝试从 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 文字。
问题
- 如何使用
|-
强制添加 block 样式的字符串? - 如何将方法添加到我的 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/