Hot*_*hke 7 python formatting yaml
这是指定PyYAML 转储部分的样式的后续问题:
考虑以下包含手动格式化 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)
Run Code Online (Sandbox Code Playgroud)
该脚本退出并显示以下输出,显示错误:
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
Run Code Online (Sandbox Code Playgroud)
你的问题是我的两个类都对字典进行操作,而不是列表。你想要一些可以与列表一起使用的东西:
class blockseqtrue( list ): pass
def blockseqtrue_rep(dumper, data):
return dumper.represent_sequence( u'tag:yaml.org,2002:seq', data, flow_style=True )
Run Code Online (Sandbox Code Playgroud)
Python 列表是 YAML 序列/seq。Python 字典是 YAML 映射/映射。
| 归档时间: |
|
| 查看次数: |
1865 次 |
| 最近记录: |