[英]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
我想將每個班級名稱和分數添加到其透視人物中。 到目前為止,我有這樣的事情:
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
我知道我的循環只返回最后一個班級名稱和分數,但我如何使用 Google Protobuf 存儲相應人員/行的每個班級和分數? 提前致謝!
您忘記添加從文件中讀取的每個人。 接下來,您需要在 person 對象中添加您找到的每個類。 您現在只創建一次這些對象,因此您會一直覆蓋它們。
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
在這里,我確實假設課程是一個重復的領域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.