pyYAML Errors on quot;!quot; in a string(“!上的 pyYAML 错误在一个字符串中)
问题描述
首先,免责声明:我对 YAML 不太熟悉.我正在尝试将 YAML 文档解析为键值对(不用担心我是怎么做的.我已经处理好了)
First, a disclaimer: I'm not too familiar with YAML. I'm trying to parse a YAML doc into Key Value Pairs (don't worry about how I'm doing it. I've got that bit handled)
我的文件曾经看起来像:
My file used to look something like:
world:
people:
name:Suzy
address:chez-bob
然后,有人去改了.
world:
people:
name:!$uzy
address:chez-bob
我得到这个解析错误:
yaml.constructor.ConstructorError: could not determine a constructor for the tag '!$uzy'
这甚至意味着什么?我将如何让它仅将 !$ 解释为两个字符?我只想要一个字符串键和值的字典!此外,编辑 yaml 文件不是一种选择.必须使用解析器在代码中修复问题.
What does this even mean? How would I go about getting it to just interpret !$ as just two characters? I just want a dictionary of string keys and values! Also, editing the yaml files is not an option. Problem must be fixed in the code using the parser.
推荐答案
感叹号是YAML标签的前缀.解析器必须通过标签名称为它实现一个构造函数.有一些默认标签,如 !!bool
、!!int
等,甚至还有一些 Python 特定标签,如 !!python/tuple
.
Exclamation mark is a prefix for YAML tags. The parser has to implement a constructor for it by the tag name. There are some default tags like !!bool
, !!int
, etc. and even some Python specific tags like !!python/tuple
.
您可以定义自己的构造函数,甚至可以为前缀捕获的多个标签定义构造函数.通过定义 ''
的前缀,您可以捕获所有标签并忽略它们.您可以从构造函数返回标签及其值,将其全部视为文本.
You can define your own constructors and even constructors for multiple tags caught by a prefix. By defining the prefix to ''
, you can catch all the tags and ignore them. You can return the tag and its value from the constructor to just treat it all as text.
>>> import yaml
>>> def default_ctor(loader, tag_suffix, node):
... print loader
... print tag_suffix
... print node
... return tag_suffix + ' ' + node.value
...
>>> yaml.add_multi_constructor('', default_ctor)
>>> yaml.load(y)
<yaml.loader.Loader object at 0xb76ce8ec>
!$uzy
ScalarNode(tag=u'!$uzy', value=u'')
{'world': {'people': {'name': '!$uzy', 'address': 'chez-bob'}}}
>>>
这篇关于“!"上的 pyYAML 错误在一个字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“!"上的 pyYAML 错误在一个字符串中


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