-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata.py
102 lines (77 loc) · 2.39 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# -*- coding: utf-8 -*-
class DataDict(object):
def __init__(self):
self._data = {}
def __repr__(self):
return '<OPUS API generic class for data objects>'
def __len__(self):
return len(self._data)
def __getitem__(self, attr):
return self._data[attr]
def __iter__(self):
return iter(self._data)
def keys(self):
return self._data.keys()
def items(self):
return self._data.items()
def values(self):
return self._data.values()
def append(self, key, value):
self._data[key] = value
def load(self, dict):
self._data = dict
def find(self, keyword):
keyword = keyword.lower()
keys = []
for key in self.keys():
if keyword in key.lower():
keys.append(key)
if len(keys) == 0:
return None
return keys
class Data(DataDict):
def __init__(self, json):
DataDict.__init__(self)
self._json = json
for row in json['page']:
el = DataElement(self.columns, row)
self._data[str(el)] = el
def __repr__(self):
return 'OPUS API Data objects (with {} elements):\n'.format(len(self)) + \
'\n'.join(' - {}'.format(key) for key, _ in self.items())
@property
def count(self):
return int(self._json['count'])
@property
def limit(self):
return int(self._json['limit'])
@property
def order(self):
return self._json['order']
@property
def page_no(self):
return int(self._json['page_no'])
@property
def labels(self):
return self._json['labels']
@property
def columns(self):
return self._json['columns']
class DataElement(DataDict):
def __init__(self, columns, row):
DataDict.__init__(self)
self._columns = columns
self._row = row
self._id = None
for column, value in zip(columns, row):
if 'OPUS ID' in str(column):
self._id = value
else:
self.append(column, value)
if self._id is None:
raise KeyError('`OPUS ID` key is missing in `cols` query')
def __repr__(self):
return 'OPUS ID: {}\n'.format(str(self)) + \
'\n'.join(' - {}: {}'.format(key, value) for key, value in self.items())
def __str__(self):
return self._id