本文介绍了PyYAML,如何对齐地图条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 PyYAML 将 Python 字典输出为 YAML 格式:

I use PyYAML to output a python dictionary to YAML format:

import yaml
d = { 'bar': { 'foo': 'hello', 'supercalifragilisticexpialidocious': 'world' } }
print yaml.dump(d, default_flow_style=False)

输出为:

bar:
  foo: hello
  supercalifragilisticexpialidocious: world

但我想:

bar:
  foo                                : hello
  supercalifragilisticexpialidocious : world

这个问题有没有简单的解决方案,甚至是次优的解决方案?

Is there a simple solution to that problem, even a suboptimal one?

推荐答案

好的,这是我目前想到的.

Ok, here is what I've come up with so far.

我的解决方案包括两个步骤.第一步定义一个字典表示,用于向键添加尾随空格.通过这一步,我在输出中获得了带引号的键.这就是为什么我添加第二个步骤来删除所有这些引号:

My solution involves two steps. The first step defines a dictionary representer for adding trailing spaces to keys. With this step, I obtain quoted keys in the output. This is why I add a second step for removing all these quotes:

import yaml
d = {'bar': {'foo': 'hello', 'supercalifragilisticexpialidocious': 'world'}}


# FIRST STEP:
#   Define a PyYAML dict representer for adding trailing spaces to keys

def dict_representer(dumper, data):
    keyWidth = max(len(k) for k in data)
    aligned = {k+' '*(keyWidth-len(k)):v for k,v in data.items()}
    return dumper.represent_mapping('tag:yaml.org,2002:map', aligned)

yaml.add_representer(dict, dict_representer)


# SECOND STEP:
#   Remove quotes in the rendered string

print(yaml.dump(d, default_flow_style=False).replace('\'', ''))

这篇关于PyYAML,如何对齐地图条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 22:47