简体   繁体   English

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

[英]Serializing data with Google Protobuf in Python

I have a text file with contents like this (format ):我有一个文本文件,内容如下(格式):

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

I would like to add each class name and score to its perspective person.我想将每个班级名称和分数添加到其透视人物中。 So far I have something like this:到目前为止,我有这样的事情:

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

I know my loop only returns the last class name and score but how do I store each of the classes and scores for the respective person/line with Google Protobuf?我知道我的循环只返回最后一个班级名称和分数,但我如何使用 Google Protobuf 存储相应人员/行的每个班级和分数? Thanks in advance!提前致谢!

You forget to add each each person you read from the file.您忘记添加从文件中读取的每个人。 Next you need to add each class your find in the person object.接下来,您需要在 person 对象中添加您找到的每个类。 You now only create those objects once and thus you overwrite them all the time.您现在只创建一次这些对象,因此您会一直覆盖它们。

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

Here I do make the assumption that courses is a repeated field.在这里,我确实假设课程是一个重复的领域。

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

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