Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - pyYAML Errors on "!" in a string

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

Then, someone went and changed it.

world:
     people:
          name:!$uzy
          address:chez-bob

And I get this parse error:

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!$uzy'

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'}}}
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...