我正在从YAML数据,这将指定由生成的每个项目YAML文件的哪一行的文件生成器。 做这个的最好方式是什么? 因此,如果YAML文件是这样的:
- key1: item 1
key2: item 2
- key1: another item 1
key2: another item 2
我想是这样的:
[
{'__line__': 1, 'key1': 'item 1', 'key2': 'item 2'},
{'__line__': 3, 'key1': 'another item 1', 'key2': 'another item 2'},
]
我目前使用PyYAML,但是任何其他库是确定的,如果我可以从Python中使用它。
我已通过添加挂钩使其Composer.compose_node
和Constructor.construct_mapping
:
import yaml
from yaml.composer import Composer
from yaml.constructor import Constructor
def main():
loader = yaml.Loader(open('data.yml').read())
def compose_node(parent, index):
# the line number where the previous token has ended (plus empty lines)
line = loader.line
node = Composer.compose_node(loader, parent, index)
node.__line__ = line + 1
return node
def construct_mapping(node, deep=False):
mapping = Constructor.construct_mapping(loader, node, deep=deep)
mapping['__line__'] = node.__line__
return mapping
loader.compose_node = compose_node
loader.construct_mapping = construct_mapping
data = loader.get_single_data()
print(data)
如果您正在使用ruamel.yaml > = 0.9(其中我的作者),并使用RoundTripLoader
,你可以访问属性lc
上收集项目获得的行和列,他们在源YAML开始:
def test_item_04(self):
data = load("""
# testing line and column based on SO
# http://stackoverflow.com/questions/13319067/
- key1: item 1
key2: item 2
- key3: another item 1
key4: another item 2
""")
assert data[0].lc.line == 2
assert data[0].lc.col == 2
assert data[1].lc.line == 4
assert data[1].lc.col == 2
(行和列0开始计数)。
这个答案显示如何将添加lc
加载过程中属性字符串类型。
下面是一个改进版本puzzlet的回答 :
import yaml
from yaml.loader import SafeLoader
class SafeLineLoader(SafeLoader):
def construct_mapping(self, node, deep=False):
mapping = super(SafeLineLoader, self).construct_mapping(node, deep=deep)
# Add 1 so line numbering starts at 1
mapping['__line__'] = node.start_mark.line + 1
return mapping
您可以使用它像这样:
data = yaml.load(whatever, Loader=SafeLineLoader)