简体   繁体   English

有什么区别! 和!! 在yaml?

[英]What is the difference between ! and !! in yaml?

I'm trying to load a YAML that looks like this: 我正在尝试加载看起来像这样的YAML:

dist: !!opencv-matrix
   rows: 380
   cols: 380
   dt: f
   data: [ 0., 0., -1.88644529e+18, 2.45423365e+00, 11698176.,
       2.03862047e+00, -8.85501460e+10, 2.54738545e+00, 1.71208843e+20,
       ...
       2.44447327e+00 ]

The loading code is just: 加载代码只是:

import yaml
y = yaml.load(s)

where s is the YAML loaded into a string. 其中s是加载到字符串中的YAML。

I get this error: 我收到此错误:

yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:opencv-matrix'
  in "<string>", line 382, column 7:
    dist: !!opencv-matrix

This is fair enough, so I add the constructor for that tag: 这很公平,所以我添加了该标记的构造函数:

def opencv_matrix(loader, node):
    mapping = loader.construct_mapping(node)
    mat = np.array(mapping["data"])
    mat.resize(mapping["rows"], mapping["cols"])
    return mat

yaml.add_constructor(u"!!opencv-matrix", opencv_matrix)
y = yaml.load(s)

I still get the error. 我仍然得到错误。 However, if I replace !!opencv_matrix with !opencv_matrix, then everything works. 但是,如果我用!opencv_matrix替换!! opencv_matrix,那么一切正常。

What's going on here? 这里发生了什么?

Secondary tags like !!opencv-matrix are actually shorthand for tag:yaml.org,2002:opencv-matrix (mentioned in the reference card ). !!opencv-matrix这样的辅助标签实际上是tag:yaml.org,2002:opencv-matrix简写tag:yaml.org,2002:opencv-matrix (在参考卡中提到)。 It looks like PyYAML's add_constructor method doesn't correctly handle this shorthand notation. 看起来PyYAML的add_constructor方法无法正确处理这种速记符号。

This may be a bug, depending on how secondary tags are interpreted (see second part below). 这可能是一个错误,具体取决于二级标记的解释方式(参见下面的第二部分)。 I've submitted a bug report here , and hopefully it will be addressed. 我在这里提交了一份错误报告,希望能够得到解决。

Primary tags like !opencv-matrix are defined explicitly, and loading seem to work without any problems in PyYAML. !opencv-matrix这样的主要标签是明确定义的,并且加载似乎在PyYAML中没有任何问题。

It works for me if you replace !!opencv-matrix with tag:yaml.org,2002:opencv-matrix in the add_constructor call. 如果你使用tag:yaml.org,2002:opencv-matrixadd_constructor调用中替换!!opencv-matrix ,它对我add_constructor


As for the original question, AFAIK primary tags ( ! ) are for user-defined types, while secondary tags ( !! ) are meant to represent standard language-independent types defined here (hence the long and fancy format). 至于原始问题,AFAIK主标签( ! )用于用户定义类型,而辅助标签( !! )用于表示此处定义的标准语言无关类型(因此是长格式和花式格式)。

If this is an OpenCV-generated file, then maybe it would probably be simpler if these tags were changed to primary tags in the application. 如果这是一个OpenCV生成的文件,那么如果将这些标记更改为应用程序中的主标记可能会更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM