mou*_*iel 5 python yaml pyyaml
我使用PyYAML将python字典输出为YAML格式:
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
有没有一个简单的解决方案,甚至是次优方案?
好的,这是我到目前为止提出的。
我的解决方案涉及两个步骤。第一步定义一个字典表示法,用于在键上添加尾随空格。通过此步骤,我将在输出中获取带引号的键。这就是为什么我添加第二步删除所有这些引号的原因:
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('\'', ''))
| 归档时间: | 
 | 
| 查看次数: | 542 次 | 
| 最近记录: |