rewrite parsing code in file.py to be more class-based

This commit is contained in:
randomuser 2021-11-22 18:16:40 -06:00
parent d408a990f5
commit b5aec5940e
3 changed files with 100 additions and 0 deletions

26
datafile Normal file
View File

@ -0,0 +1,26 @@
cat test:
foo: bar
rec f0000:
date: 01-23-1998
inherit: test
inherit_order: 1
rec f0001:
date: 09-22-1998
inherit: test
inherit_order: 2
cat g0002:
inherit: test
inherit_order: 3
rec f0003:
date: 09-19-1998
inherit: g0002
inherit_order: 1
rec f0004:
date: 09-21-1998
inherit: g0002
inherit_order: 2

69
record.py Normal file
View File

@ -0,0 +1,69 @@
class FileParsingError(SyntaxError):
pass
class Record:
def __init__(self):
self.name = None
self.data = {}
self.children = {}
self.parents = {}
def __getitem__(self, item):
return self.data[item]
def __setitem__(self, item, value):
self.data[item] = value
def __repr__(self):
return f"[{self.data}, {len(self.children)}, {len(self.parents)}]"
class RecordCollection():
def __init__(self, file):
if type(file) is str:
fd = open(file, "r")
elif hasattr(file, "read"):
fd = file
self._fromFile(fd)
self._parent()
def _fromFile(self, fd):
lines = [i.rstrip() for i in fd.readlines()]
self.objects = {}
current = Record()
for i in lines:
ind = i[0:2] == ' '
if ind:
spl = i[2:].split(': ')
try:
current[spl[0]] = spl[1]
except IndexError:
raise FileParsingError(f"error parsing '{i}'")
else:
try:
name = i.split(' ')[1][0:-1]
except IndexError:
current = Record()
continue
current.name = name
self.objects[name] = current
def _parent(self):
for i in self.objects:
current = self.objects[i]
try:
for j, k in zip(
current['inherit'].split(' '),
[int(i) for i in current['inherit_order'].split(' ')]
):
current.parents[j] = self.objects[j]
self.objects[j].children[k] = current
except KeyError:
pass

5
record_test.py Normal file
View File

@ -0,0 +1,5 @@
import record
records = record.RecordCollection('datafile')
print(records.objects)