[我正在尝试从官方Google字体存储库中解析METADATA.pb文件,该文件可在以下位置找到:https://github.com/google/fonts(Roboto字体的示例METADATA.pb文件:https://github.com/google/fonts/blob/master/apache/roboto/METADATA.pb)
要解析原始buf文件,需要正确的格式。可以在此处下载为“ public_fonts.proto”:https://github.com/googlefonts/gftools/blob/master/Lib/gftools/fonts_public.proto
我用它通过以下命令生成了一个名为“ fonts_public_pb2.py”的Python代码文件:
protoc -I=. --python_out=. fonts_public.proto
这是我的代码,该代码导入此生成的文件,读取METADATA.pb文件的内容(无论哪个,它们都遵循相同的结构,然后尝试解析原始Buf字符串。
#! /usr/bin/env python
import fonts_public_pb2
protobuf_file_path = 'METADATA.pb'
protobuf_file = open(protobuf_file_path, 'rb')
protobuf = protobuf_file.read()
font_family = fonts_public_pb2.FamilyProto()
font_family.ParseFromString(protobuf)
仅几行,没有什么太复杂,但是输出始终是相同的:
Traceback (most recent call last):
File "parse.py", line 22, in <module>
font_family.ParseFromString(protobuf)
google.protobuf.message.DecodeError: Error parsing message
我通常不使用Python编写代码,所以这里的问题很可能是我自己,但是尝试了几种不同的操作后,我不知道该怎么做了:
那些METADATA.pb文件不是二进制protobuf文件,它们使用text format。
import fonts_public_pb2
from google.protobuf import text_format
protobuf_file_path = 'METADATA.pb'
protobuf_file = open(protobuf_file_path, 'r')
protobuf = protobuf_file.read()
font_family = fonts_public_pb2.FamilyProto()
text_format.Merge(protobuf, font_family)
print(font_family)