0

原始 YAML 文件是

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: gut
  #comment5

在python中,我做到了

yml = ruamel.yaml.round_trip_load(yaml_input_str)
exec("del yml['toplevel']['gets']")
output_str = ruamel.yaml.round_trip_dump(yml)

output_str 变为

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment5

和comment3 和comment4 消失。这是设计的还是错误的?

4

1 回答 1

0

就是这样设计的。但是,正如 ruamel.yaml 的大部分内容一样,未充分记录,主要是由于包作者的懒惰。

注释与键相关联,而不是与相对于映射开头的某个位置相关联。由于 YAML 被标记化的方式,注释与以下键相关联。这样做的结果是,如果不再有键,注释仍然可用,但不再发出。

这样做的副作用是,如果你这样做:

import sys
import ruamel.yaml

yaml_str = """\
toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: gut
  #comment5
"""

data = ruamel.yaml.round_trip_load(yaml_str)
del data['toplevel']['gets']
ruamel.yaml.round_trip_dump(data, sys.stdout)

你得到你的output_str,然后如果你遵循:

data['toplevel']['gets'] = 42
ruamel.yaml.round_trip_dump(data, sys.stdout)

你会得到:

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: 42
  #comment5

所以评论“神奇地”重新出现。

如果要将注释移动到嵌套映射的末尾(使用键 'toplevel'),可以执行以下操作:

comment_tokens = data['toplevel'].ca.items['gets'][1]
del data['toplevel'].ca.items['gets']  # not strictly necessary
data['toplevel'].ca.end = comment_tokens

你会得到:

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  #comment5

这可能是您最初所期望的。


这让我想知道为什么你使用exec()而不是直接使用:

del yml['toplevel']['gets']
于 2016-11-29T19:39:50.693 回答