首先,免责声明:我对 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 错误在一个字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!