import sys
import argparse
import os.path
import netstruct
#parseaza un string in format binar lungime+caractere, to UTF-8
def unpackString(d):
return str(netstruct.unpack(b"b$",d)[0],'UTF-8',errors="ignore")
#parseaza itemii de raspuns
def unpackItems(d):
items = []
num = netstruct.unpack(b"b",d[:1])
for n in range(num[0]):
items.append(unpackString(d[256*n+1:]))
return items
#parseaza ultimul byte, numarul intrebarii corecte
def unpackCorrectAnswer(d):
return netstruct.unpack(b"b",d)
#deschide fisierul
with open("test internet9.tst", "rb") as f:
#fiecare intrebare are 1589 byte
b = f.read(1589)
while b:
#parsam fiecare intrebare in bloc de 1588 bytes
#primii 51b sunt numele testului
numetest = unpackString(b[:51])
#urmatorii 255b sunt textul intrebarii
intrebare = unpackString(b[51:51+255])
#urmeaza un vecor de itemi de raspuns (parsat caz special)
items = unpackItems(b[307:-1])
#ultimul byte e numarul intrebarii corecte
answer = unpackCorrectAnswer(b[1588:])
print(numetest)
print(intrebare)
print(items)
print(answer[0])
print("=================")
b = f.read(1589)
Nu ma pricep la python structs asa ca am folosit netstruct. Il iei easy cu
pip install netstruct
Scriptul e cam spaghetti dar face si afisarea intrebarilor si raspunsurilor. "unpackItems" e cea mai complexa, in rest implementarea e foarte directa