在 Python 中使用 Google Protobuf 序列化数据

Serializing data with Google Protobuf in Python

我有一个文本文件,内容如下(格式):

Alice:ECE505,56:HIS230,78:REC345,98
Bob:MATH300,78:IN121,79:LEC091,23:ARC,32:WER720,67

我想将每个 class 的名字和分数添加到它的视角人物中。 到目前为止,我有这样的东西:

all_stu = record_pb2.Result()
person = all_stu.student.add()
cl = person.courses.add()

with open(textfile, "r") as readfile:
    txt = readfile.read()
    for line in txt.split('\n'):
        segment = line.split(':')
        person.name = segment[0]

        classes = segment[1:]

        #I have tried this but it only returns the last class and score 
        for c in classes:
            cname, score = c.split(',')
            cl.name = cname
            cl.score = score

我只知道我的循环 returns 最后一个 class 名称和分数但是我如何存储每个 classes 和相应 person/line 的分数Google 协议缓冲区?提前致谢!

您忘记添加您从文件中读取的每个人。接下来,您需要添加每个 class 您在人员对象中找到的内容。您现在只创建这些对象一次,因此您会一直覆盖它们。

all_stu = record_pb2.Result()
person = all_stu.student.add()

with open(textfile, "r") as readfile:
    txt = readfile.read()
    for line in txt.split('\n'):
        segment = line.split(':')

        person = all_stu.student.add()
        person.name = segment[0]

        classes = segment[1:]

        #I have tried this but it only returns the last class and score 
        for c in classes:
            cl = person.courses.add()
            cname, score = c.split(',')
            cl.name = cname
            cl.score = score

这里我假设 courses 是一个重复字段。