如何控制 PyYAML 用于我的数据的标量形式? [英] How can I control what scalar form PyYAML uses for my data?

查看:54
本文介绍了如何控制 PyYAML 用于我的数据的标量形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有短字符串属性和长多行字符串属性的对象.我想将短字符串写为 YAML 引用的标量,将多行字符串写为文字标量:

I've got an object with a short string attribute, and a long multi-line string attribute. I want to write the short string as a YAML quoted scalar, and the multi-line string as a literal scalar:

my_obj.short = "Hello"
my_obj.long = "Line1\nLine2\nLine3"

我希望 YAML 看起来像这样:

I'd like the YAML to look like this:

short: "Hello"
long: |
  Line1
  Line2
  Line3

如何指示 PyYAML 执行此操作?如果我调用 yaml.dump(my_obj),它会产生一个类似 dict 的输出:

How can I instruct PyYAML to do this? If I call yaml.dump(my_obj), it produces a dict-like output:

{long: 'line1

    line2

    line3

    ', short: Hello}

(不知道为什么 long 是这样的双倍行距...)

(Not sure why long is double-spaced like that...)

我可以指示 PyYAML 如何处理我的属性吗?我想同时影响顺序和样式.

Can I dictate to PyYAML how to treat my attributes? I'd like to affect both the order and style.

推荐答案

基于 Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库?

import yaml
from collections import OrderedDict

class quoted(str):
    pass

def quoted_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
yaml.add_representer(quoted, quoted_presenter)

class literal(str):
    pass

def literal_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)

def ordered_dict_presenter(dumper, data):
    return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)

d = OrderedDict(short=quoted("Hello"), long=literal("Line1\nLine2\nLine3\n"))

print(yaml.dump(d))

输出

short: "Hello"
long: |
  Line1
  Line2
  Line3

这篇关于如何控制 PyYAML 用于我的数据的标量形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆