Python Pyaml,如何对齐地图条目?
我使用PyYAML将python字典输出为YAML格式:Python Pyaml,如何对齐地图条目?,python,yaml,pyyaml,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: fo
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
这个问题有没有简单的解决方案,哪怕是次优的 好的,这是我到目前为止的想法 我的解决方案包括两个步骤。第一步定义字典representer,用于向键添加尾随空格。通过这一步,我在输出中获得带引号的键。这就是我添加第二步删除所有这些引号的原因:
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('\'', ''))
我找到了JavaScript,并在
它不使用PyYAML,直接将其应用于YAML输出,无需解析
以下功能的副本:
import re
def align_yaml(str, pad=0):
props = re.findall(r'^\s*[\S]+:', str, re.MULTILINE)
longest = max([len(i) for i in props]) + pad
return ''.join([i+'\n' for i in map(lambda str:
re.sub(r'^(\s*.+?[^:#]: )\s*(.*)', lambda m:
m.group(1) + ''.ljust(longest - len(m.group(1)) + 1) + m.group(2),
str, re.MULTILINE)
, str.split('\n'))])
在快速查看了
PyYAML
源代码之后,我认为这并不容易实现。它至少需要创建一个自定义的发射器
(或修补现有的发射器)。虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-很容易做到,但我有点不同意这个概念。复制的代码可能会过时。我猜选择也应该取决于被链接的站点的声誉?不,站点链接本身仍然可以作为补充提供。必须在这里找到答案的关键部分