-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSPARQLEngine.py
55 lines (47 loc) · 1.39 KB
/
SPARQLEngine.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
"""
Sparql Engine class to run the queries
"""
import re
from typing import List, Tuple
import owlready2 as owl
class SPARQLEngine:
"""
Sparql Engine class to run the queries
Parameters
----------
file_path : str
The path to the ontology file
"""
def __init__(self, file_path: str):
self.world = owl.World()
self.onto = self.world.get_ontology(file_path).load()
self.graph = self.world.as_rdflib_graph()
def run_query(self, query: str) -> Tuple[List[str], List[List[str]]]:
"""
Run a sparql query
Parameters
----------
query : str
The sparql query
Returns
-------
Tuple[List[str], List[List[str]]]
The headers and results of the query
"""
results = self.graph.query(query)
try:
headers = [str(header) for header in results.vars]
except:
headers = []
parsed_results = []
for row in results:
to_add = []
for element in row:
if element is None:
parsed = "-"
else:
parsed = element.n3().replace(">", "").replace("<", "")
parsed = re.sub("http:.*#", "", parsed)
to_add.append(parsed)
parsed_results.append(to_add)
return headers, parsed_results