Parsing YAML, return with line number(解析 YAML,返回行号)
本文介绍了解析 YAML,返回行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用 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 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)
这篇关于解析 YAML,返回行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:解析 YAML,返回行号


基础教程推荐
猜你喜欢
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01