-
Notifications
You must be signed in to change notification settings - Fork 0
/
hierarchy_traversal.py
46 lines (38 loc) · 1.8 KB
/
hierarchy_traversal.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
class HierarchyTraversal:
@staticmethod
def traverse(hierarchy, task_creator):
HierarchyTraversal._traverse(node=hierarchy.root_node, path="root", task_creator=task_creator)
@staticmethod
def _traverse(node, path, task_creator):
if not node.is_leaf():
property_entity_dict = {}
for child in node.children:
child_predicate = HierarchyTraversal.extract_wikidata_id(child.label[0].value)
child_object = HierarchyTraversal.extract_wikidata_id(child.label[1].value)
child_entities = HierarchyTraversal._traverse(child, path + "/" + child_predicate + "/" + child_object,
task_creator)
property_entities = property_entity_dict.get(child_predicate, None)
if property_entities is None:
property_entities = []
property_entity_dict[child_predicate] = property_entities
property_entities.extend(child_entities)
# für jedes P
for predicate, predicate_entities in property_entity_dict.items():
task_creator.process_node(path + '/' + predicate, node, predicate_entities, True)
entities = HierarchyTraversal.extract_wikidata_ids(node)
# für jedes Q
task_creator.process_node(path, node, entities, False)
return entities
@staticmethod
def extract_wikidata_id(uri):
return uri.split('/')[-1]
@staticmethod
def build_path(stack):
return '/'.join(stack)
@staticmethod
def extract_wikidata_ids(node):
ids = []
for entity in node.values:
wikidata_id = HierarchyTraversal.extract_wikidata_id(entity.value)
ids.append(wikidata_id)
return ids