转储的一部分指定样式

转储的一部分指定样式

本文介绍了为 PyYAML 转储的一部分指定样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 YAML 用于计算机,将人工可编辑和可读的输入格式用于模拟器.对于人类可读性,输入的某些部分大多适合块样式,而流样式更适合其他部分.

I'm using YAML for a computer and human-editable and readable input format for a simulator. For human readability, some parts of the input are mostly amenable to block style, while flow style suits others better.

PyYAML 的默认设置是在有嵌套映射或序列的地方使用块样式,在其他地方使用流样式.*default_flow_style* 允许选择全流式或全块式.

The default for PyYAML is to use block style wherever there are nested maps or sequences, and flow style everywhere else. *default_flow_style* allows one to choose all-flow-style or all-block-style.

但我想输出更多格式的文件

But I'd like to output files more of the form

bonds:
- { strength: 2.0 }
- ...
tiles:
- { color: red, edges: [1, 0, 0, 1], stoic: 0.1}
- ...
args:
    block: 2
    Gse: 9.4

可以看出,这并没有遵循始终一致的样式模式,而是根据文件的部分而变化.本质上,我希望能够指定某些块样式序列中的所有值都是流样式.有什么方法可以对倾销进行精细控制吗?能够以特定顺序转储顶级映射而不需要该顺序(例如,omap)对于可读性也很好.

As can be seen, this doesn't follow a consistent pattern for styles throughout, and instead changes depending upon the part of the file. Essentially, I'd like to be able to specify that all values in some block style sequences be in flow style. Is there some way to get that sort of fine-level control over dumping? Being able to dump the top-level mapping in a particular order while not requiring that order (eg, omap) would be nice as well for readability.

推荐答案

事实证明,这可以通过为我不想遵循 default_flow_style 的每个项目定义具有表示器的子类来完成,然后在转储之前将所有必要的内容转换为那些.在这种情况下,这意味着我会得到类似的东西:

It turns out this can be done by defining subclasses with representers for each item I want not to follow default_flow_style, and then converting everything necessary to those before dumping. In this case, that means I get something like:

class blockseq( dict ): pass
def blockseq_rep(dumper, data):
    return dumper.represent_mapping( u'tag:yaml.org,2002:map', 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 )

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

def dump( st ):
    st['tiles'] = [ flowmap(x) for x in st['tiles'] ]
    st['bonds'] = [ flowmap(x) for x in st['bonds'] ]
    if 'xgrowargs' in st.keys(): st['xgrowargs'] = blockseq(st['xgrowargs'])
    return yaml.dump(st)

烦人的是,更易于使用的 dumper.represent_list 和 dumper.represent_dict 不允许指定 flow_style,所以我必须指定标签,但系统确实可以工作.

Annoyingly, the easier-to-use dumper.represent_list and dumper.represent_dict don't allow flow_style to be specified, so I have to specify the tag, but the system does work.

这篇关于为 PyYAML 转储的一部分指定样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:25