gpt4 book ai didi

python - PyYAML,如何对齐 map 条目?

转载 作者:太空狗 更新时间:2023-10-30 01:09:28 25 4
gpt4 key购买 nike

我使用 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('\'', ''))

关于python - PyYAML,如何对齐 map 条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com