26

我希望能够转储包含长字符串的字典,我希望在块样式中具有可读性。例如:

foo: |
  this is a
  block literal
bar: >
  this is a
  folded block

PyYAML 支持加载具有这种样式的文档,但我似乎找不到以这种方式转储文档的方法。我错过了什么吗?

4

3 回答 3

34
import yaml

class folded_unicode(unicode): pass
class literal_unicode(unicode): pass

def folded_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)

data = {
    'literal':literal_unicode(
        u'by hjw              ___\n'
         '   __              /.-.\\\n'
         '  /  )_____________\\\\  Y\n'
         ' /_ /=== == === === =\\ _\\_\n'
         '( /)=== == === === == Y   \\\n'
         ' `-------------------(  o  )\n'
         '                      \\___/\n'),
    'folded': folded_unicode(
        u'It removes all ordinary curses from all equipped items. '
        'Heavy or permanent curses are unaffected.\n')}

print yaml.dump(data)

结果:

folded: >
  It removes all ordinary curses from all equipped items. Heavy or permanent curses
  are unaffected.
literal: |
  by hjw              ___
     __              /.-.\
    /  )_____________\\  Y
   /_ /=== == === === =\ _\_
  ( /)=== == === === == Y   \
   `-------------------(  o  )
                        \___/

为了完整起见,还应该有 str 实现,但我会偷懒:-)

于 2011-09-16T13:38:48.680 回答
23

pyyaml确实支持转储文字或折叠块。

使用Representer.add_representer

定义类型:

class folded_str(str): pass

class literal_str(str): pass

class folded_unicode(unicode): pass

class literal_unicode(str): pass

然后,您可以为这些类型定义代表。请注意,虽然Gary解决方案适用于 unicode,但您可能需要做更多的工作才能使字符串正常工作(请参阅表示的实现)。

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

# represent_str does handle some corner cases, so use that
# instead of calling represent_scalar directly
represent_folded_str = change_style('>', SafeRepresenter.represent_str)
represent_literal_str = change_style('|', SafeRepresenter.represent_str)
represent_folded_unicode = change_style('>', SafeRepresenter.represent_unicode)
represent_literal_unicode = change_style('|', SafeRepresenter.represent_unicode)

然后您可以将这些代表添加到默认转储程序中:

yaml.add_representer(folded_str, represent_folded_str)
yaml.add_representer(literal_str, represent_literal_str)
yaml.add_representer(folded_unicode, represent_folded_unicode)
yaml.add_representer(literal_unicode, represent_literal_unicode)

...并测试它:

data = {
    'foo': literal_str('this is a\nblock literal'),
    'bar': folded_unicode('this is a folded block'),
}

print yaml.dump(data)

结果:

bar: >-
  this is a folded block
foo: |-
  this is a
  block literal

使用default_style

如果您有兴趣让所有字符串都遵循默认样式,您还可以使用default_style关键字参数,例如:

>>> data = { 'foo': 'line1\nline2\nline3' }
>>> print yaml.dump(data, default_style='|')
"foo": |-
  line1
  line2
  line3

或对于折叠文字:

>>> print yaml.dump(data, default_style='>')
"foo": >-
  line1

  line2

  line3

或者对于双引号文字:

>>> print yaml.dump(data, default_style='"')
"foo": "line1\nline2\nline3"

注意事项:

这是您可能没想到的示例:

data = {
    'foo': literal_str('this is a\nblock literal'),
    'bar': folded_unicode('this is a folded block'),
    'non-printable': literal_unicode('this has a \t tab in it'),
    'leading': literal_unicode('   with leading white spaces'),
    'trailing': literal_unicode('with trailing white spaces  '),
}
print yaml.dump(data)

结果是:

bar: >-
  this is a folded block
foo: |-
  this is a
  block literal
leading: |2-
     with leading white spaces
non-printable: "this has a \t tab in it"
trailing: "with trailing white spaces  "

1) 不可打印字符

有关转义字符,请参阅 YAML 规范(第 5.7 节):

请注意,转义序列仅在双引号标量中解释。在所有其他标量样式中,“\”字符没有特殊含义,并且不可打印字符不可用。

如果要保留不可打印的字符(例如 TAB),则需要使用双引号标量。如果您能够转储具有文字样式的标量,并且其中有不可打印的字符(例如 TAB),则您的 YAML 转储程序不兼容。

例如,即使指定了默认样式,也会pyyaml检测到不可打印的字符并使用双引号样式:\t

>>> data = { 'foo': 'line1\nline2\n\tline3' }
>>> print yaml.dump(data, default_style='"')
"foo": "line1\nline2\n\tline3"

>>> print yaml.dump(data, default_style='>')
"foo": "line1\nline2\n\tline3"

>>> print yaml.dump(data, default_style='|')
"foo": "line1\nline2\n\tline3"

2) 前导和尾随空格

规范中的另一点有用信息是:

所有前导和尾随空白字符都从内容中排除

这意味着如果您的字符串确实有前导或尾随空格,则它们不会以双引号以外的标量样式保留。因此,pyyaml尝试检测标量中的内容并可能强制使用双引号样式。

于 2013-12-31T22:40:04.227 回答
1

这可以相对容易地完成,唯一的“障碍”是如何指示字符串中需要表示为折叠标量的哪些空格需要变成折叠。文字标量具有包含该信息的显式换行符,但这不能用于折叠标量,因为它们可以包含显式换行符,例如,如果有前导空格并且在末尾还需要一个换行符,以便不使用剥离 chomping 表示指标 ( >-)

import sys
import ruamel.yaml

folded = ruamel.yaml.scalarstring.FoldedScalarString
literal = ruamel.yaml.scalarstring.LiteralScalarString

yaml = ruamel.yaml.YAML()

data = dict(
    foo=literal('this is a\nblock literal\n'), 
    bar=folded('this is a folded block\n'),
)

data['bar'].fold_pos = [data['bar'].index(' folded')]

yaml.dump(data, sys.stdout)

这使:

foo: |
  this is a
  block literal
bar: >
  this is a
  folded block

fold_pos属性需要一个可逆的迭代,表示空间的位置,指示折叠的位置。

如果您的字符串中从未有管道字符('|'),您可以执行以下操作:

import re

s = 'this is a|folded block\n'
sf = folded(s.replace('|', ' '))  # need to have a space!
sf.fold_pos = [x.start() for x in re.finditer('\|', s)]  # | is special in re, needs escaping


data = dict(
    foo=literal('this is a\nblock literal\n'), 
    bar=sf,  # need to have a space
)

yaml = ruamel.yaml.YAML()
yaml.dump(data, sys.stdout)

这也给出了你期望的输出

于 2018-08-23T07:35:07.170 回答