【问题标题】:Specifying styles for portions of a PyYAML dump (II): sequences指定 PyYAML 转储部分的样式 (II):序列
【发布时间】:2015-05-12 12:27:09
【问题描述】:

这是Specifying styles for portions of a PyYAML dump的后续问题:

考虑以下代码包含作为输入手动格式化的 YAML 数据。我正在修改 YAML 数据,但希望在写入的 YAML 文件中保持单行的边缘。

import yaml

st2 = yaml.load("""
edges:
- [1, 2]
- [2, 1, [1,0]]
""")
print yaml.dump(st2)

class blockseq( dict ): pass
def blockseq_rep(dumper, data):
    return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=False )

class flowmap( dict ): pass
def flowmap_rep(dumper, data):
    return dumper.represent_mapping( u'tag:yaml.org,2002:map', data, flow_style=True )

class blockseqtrue( dict ): pass
def blockseqtrue_rep(dumper, data):
    return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=True )

yaml.add_representer(blockseq, blockseq_rep)
yaml.add_representer(blockseqtrue, blockseqtrue_rep)
yaml.add_representer(flowmap, flowmap_rep)

st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ]
print yaml.dump(st2)

此脚本退出并显示错误的以下输出:

edges:
- [1, 2]
- - 2
  - 1
  - [1, 0]  

Traceback (most recent call last):
  File "test-yaml-rep.py", line 42, in <module>
    st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ]
TypeError: cannot convert dictionary update sequence element #0 to a sequence 

【问题讨论】:

    标签: python formatting yaml


    【解决方案1】:

    您的问题是我拥有的两个类都在字典上运行,而不是列表。您想要一些适用于列表的东西:

    class blockseqtrue( list ): pass
    def blockseqtrue_rep(dumper, data):
        return dumper.represent_sequence( u'tag:yaml.org,2002:seq', data, flow_style=True )
    

    Python 列表是 YAML 序列/序列。 Python dicts 是 YAML 映射/映射。

    【讨论】:

      【解决方案2】:

      如果您在 python 中执行往返 YAML,那么使用 ruamel.yaml 会更容易(我是 PyYAML 增强版的作者)。 它保留了流/块样式的序列/列表和映射/字典(以及 cmets):

      import ruamel.yaml
      
      st2 = ruamel.yaml.load("""
      edges:
      - [1, 2]    # <- change the second item
      - [2, 1, [1,0]]
      """, Loader=ruamel.yaml.RoundTripLoader)
      
      st2['edges'][0][1] = 42
      print(ruamel.yaml.dump(st2, Dumper=ruamel.yaml.RoundTripDumper))
      

      会给你:

      edges:
      - [1, 42]   # <- change the second item
      - [2, 1, [1, 0]]
      

      如您所见,这保留了最顶层序列的块样式(edges 的值)和其他序列的流样式。

      【讨论】:

        猜你喜欢
        • 2012-12-09
        • 2014-01-15
        • 1970-01-01
        • 2012-12-23
        • 2021-05-20
        • 1970-01-01
        • 2017-08-08
        • 2012-12-11
        相关资源
        最近更新 更多