解析 YAML,返回行号

编程入门 行业动态 更新时间:2024-10-28 05:20:15
问题描述

我正在用 YAML 数据制作一个文档生成器,它将指定每个项目是从 YAML 文件的哪一行生成的.做这个的最好方式是什么?所以如果 YAML 文件是这样的:

I'm making a document generator from YAML data, which would specify which line of the YAML file each item is generated from. What is the best way to do this? So if the YAML file is like this:

- 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 中使用它,任何其他库都可以.

I'm currently using PyYAML, but any other library is OK if I can use it from Python.

推荐答案

这是puzzlet的答案的改进版:

import yamlfrom yaml.loader import SafeLoaderclass 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)
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

解析 YAML,返回行号

本文发布于:2023-05-22 18:52:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!