代码之家  ›  专栏  ›  技术社区  ›  Lolo

如何解析protobuf文件中缺少引号的字符串字段?

  •  0
  • Lolo  · 技术社区  · 7 年前

    我试图解析一个protobuf文件,其中一个字段是一个没有引号的字符串。因此,我使用的解析器将该字段读取为int。我想提取实际字符串。

    在下面的示例中,如何将此字段(类型)解析为字符串“卷积”,而不是4?

    >>> import numpy as np
    >>> import sys, os
    >>> import argparse
    >>> import caffe_quant_pb2 as cq
    >>> from google.protobuf import text_format
    >>> f = open('models/vgg/deploy.prototxt', 'r')
    >>> net_txt = cq.NetParameter()
    >>> text_format.Parse(f.read(), net_txt)
    name: "VGG_ILSVRC_16_layers"
    layers {
      bottom: "data"
      top: "conv1_1"
      name: "conv1_1"
      type: CONVOLUTION
      convolution_param {
        num_output: 64
        pad: 1
        kernel_size: 3
      }
    }
    >>> print net_txt.layers[0].name  # works as I expect
    conv1_1
    >>> print net_txt.layers[0].type  # reads CONVOLUTION as the 'int' 4
    4
    >>> print type(net_txt.layers[0].type)
    <type 'int'>
    >>> print str("CONVOLUTION" == net_txt.layers[0].type)
    False
    >>> print str(net_txt.layers[0].type)
    4
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Luc    7 年前

    您正在尝试读取其中的枚举: https://developers.google.com/protocol-buffers/docs/reference/python-generated#enum

    转换为字符串可能不是最优雅的方式。

    我认为这应该是真的:

    print str(cq.V1LayerParameter.LayerType.DESCRIPTOR.values_by_name["CONVOLUTION"].number == net_txt.layers[0].type)
    
    推荐文章