我需要获取 YAML 文件中某些键的行号。
请注意,这个答案没有解决问题:我确实使用鲁梅尔.yaml,并且答案不适用于有序地图。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ruamel import yaml
data = yaml.round_trip_load("""
key1: !!omap
- key2: item2
- key3: item3
- key4: !!omap
- key5: item5
- key6: item6
""")
print(data)
结果我得到这个:
CommentedMap([('key1', CommentedOrderedMap([('key2', 'item2'), ('key3', 'item3'), ('key4', CommentedOrderedMap([('key5', 'item5'), ('key6', 'item6')]))]))])
什么不允许访问行号,除了!!omap
keys:
print(data['key1'].lc.line) # output: 1
print(data['key1']['key4'].lc.line) # output: 4
but:
print(data['key1']['key2'].lc.line) # output: AttributeError: 'str' object has no attribute 'lc'
Indeed, data['key1']['key2]
is a str
.
我找到了一个解决方法:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ruamel import yaml
DATA = yaml.round_trip_load("""
key1: !!omap
- key2: item2
- key3: item3
- key4: !!omap
- key5: item5
- key6: item6
""")
def get_line_nb(data):
if isinstance(data, dict):
offset = data.lc.line
for i, key in enumerate(data):
if isinstance(data[key], dict):
get_line_nb(data[key])
else:
print('{}|{} found in line {}\n'
.format(key, data[key], offset + i + 1))
get_line_nb(DATA)
output:
key2|item2 found in line 2
key3|item3 found in line 3
key5|item5 found in line 5
key6|item6 found in line 6
但这看起来有点“脏”。有更合适的方法吗?
编辑:这种解决方法不仅脏,而且只适用于像上面这样的简单情况,并且一旦存在嵌套列表就会给出错误的结果