0

我想保存这本词典

data = { yaml: { l: 'hi\nif x = y:\n  print z\n' } }

在 YAML 中使用 Python。当我使用yaml.dump(data, default_flow_style=False)时,输出是:

yaml: 
  l: "hi\nif x = y:\n  print z\n"

但我知道 YAML 有这种格式:

yaml: 
  l:
    |
    hi
    if x = y:
      print z

我应该怎么做才能以上述格式输出?

4

1 回答 1

1

尝试使用 YAML 标量:

YAML 标量

import yaml
from collections import OrderedDict    

class literal(str): pass

def literal_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)

def ordered_dict_presenter(dumper, data):
    return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)

d_temp = OrderedDict(l=literal('hi\nif x = y:\n print z\n'))
d = OrderedDict(yaml=literal(yaml.dump(d_temp)))
print(yaml.dump(d))

输出:

 yaml: |
      l: |
        hi
        if x = y:
         print z

希望这对你有用...

于 2013-08-21T11:32:42.370 回答