YAML在文件中附加DATA

时间:2016-08-18 06:57:49

标签: yaml pyyaml

我有一个这样的YAML文件:

Main_part1:
   label1: Main PArt1


Main_part2:
   label2: Main Part2


A_part1:
  label3: part1 of A

A_part2:
   label4: part 2 of A

B_part1:
    label5: this is part 1 of B

B_part2:
  label6: this is part 2 of B

我有一个带有2个<div>标记的html文件,用于A和B.每当点击A时,A_part1的内容应追加到Main_part1A_part2应附加到Main_part2的内容。同样地,对于B.并将回复发送回网页,其中添加了A / B的内容。

最后,我想创建一个合并Main_Part1Main_Part2的最终YAML文件。

可以使用任何类型的解决方案(Java / Python等)。

我创建了不同的标签,以显示所有块中的内部信息都不同。举个例子:

假设您单击A,YAML文件将如下所示:

Main_part1:
   label1: Main PArt1
   label3: part1 of A
Main_part2:
   label2: Main Part2
   label4: part 2 of A

A_part1:
   label3: part1 of A

A_part2:
   label4: part 2 of A

B_part1:
   label5: this is part 1 of B

B_part2:
   label6: this is part 2 of B

然后合并Main_part1Main_part2的最终YAML文件。

1 个答案:

答案 0 :(得分:2)

你拥有它们的键对于这个操作并不是很有效,所以最好的做法是将顶层键的键解析为备用字典,键指向与原始映射/字典相同的(字典)值:

import sys
import ruamel.yaml

yaml_str = """\
Main_part1:
   label1: Main PArt1
Main_part2:
   label2: Main Part2
A_part1:
  label3: part1 of A
A_part2:
   label4: part 2 of A
B_part1:
    label5: this is part 1 of B
B_part2:
  label6: this is part 2 of B
"""

data = ruamel.yaml.round_trip_load(yaml_str)
alt = {}
for key in data:
    section, part = key.split('_')
    alt[(section, part)] = data[key]
alt[('Main', 'part1')].update(alt[('Main', 'part2')])

之后你需要一个小帮手,调用它并转储原始文件:

def collapse(collapse_key):
    for key in alt:
        if key[0] == collapse_key:
            alt[('Main', key[1])].update(alt[key])

collapse('A')  # <- this should be a parameter to your script based on the click.

ruamel.yaml.round_trip_dump(data, sys.stdout)

给出:

Main_part1:
  label1: Main PArt1
  label3: part1 of A
  label2: Main Part2
  label4: part 2 of A
Main_part2:
  label2: Main Part2
  label4: part 2 of A
A_part1:
  label3: part1 of A
A_part2:
  label4: part 2 of A
B_part1:
  label5: this is part 1 of B
B_part2:
  label6: this is part 2 of B

如果以某种方式创建密钥,那当然会更容易一些 你将使用它们(即有两个元素):

(Main, part1):
   label1: Main PArt1
(Main, part2):
   label2: Main Part2
(A, part1):
  label3: part1 of A
(A, part2):
   label4: part 2 of A
(B, part1):
    label5: this is part 1 of B
(B, part2):
  label6: this is part 2 of B

以上是非常好的YAML,虽然并非所有解析器都接受。