【发布时间】: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