import re
import yaml
# 変更前の入力データ
input_data = """
<tag1>
2
foo
1 2 3
bar
1 2 3
</tag1>
<tag2>
2
ame
1 2 3
yuu
1 2 3
</tag2>
"""
# 正規表現を使用して各 <tag> セクションごとに情報を抽出
matches = re.findall(r'<(\w+)>\s*(.*?)\s*</\1>', input_data, re.DOTALL)
# YAML形式のデータを格納するための辞書
output_dict = {}
# 各 <tag> セクションごとに処理
for tag, content in matches:
# YAML形式のデータを格納するための辞書
tag_dict = {}
# 抽出した情報を処理して辞書に格納
lines = content.strip().split('\n')
key = None
values = []
for line in lines:
if line.strip():
if not key:
key = line.strip()
else:
values.append(line.strip())
# 各 <tag> セクションのデータを output_dict に追加
tag_dict[key] = values
output_dict[tag] = tag_dict
# YAML形式に変換
output_yaml = yaml.dump(output_dict, default_flow_style=False)
# 結果の出力
print(output_yaml)