-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPARQLProcessor.py
More file actions
104 lines (66 loc) · 2.21 KB
/
SPARQLProcessor.py
File metadata and controls
104 lines (66 loc) · 2.21 KB
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
103
104
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 23:11:32 2020
@author: Eduardo Vicente
"""
import pandas as pd
import rdflib
from rdflib import Graph, Namespace
import rdflib.plugins.sparql as SPARQL
import json
def load_dict(filename):
with open(filename,'r') as f:
dict_pred_obj = json.load(f)
return dict_pred_obj
def load_rdf(filename):
graph = Graph()
graph.parse(filename, format="turtle")
return graph
def process_nlp_input(nlp_values):
print(nlp_values[2])
return ""
def do_sparql_query(dic,rdf_graph):
results = []
response = ""
ns1 = Namespace("http://example.org/")
q_header = "SELECT ?s WHERE { "
q_foot = "}"
where_feat = []
for key,value in dic.items():
where_feat.append('?s ns1:'+key+" '"+value+"' "+". ")
for i in range(len(where_feat)):
q_header = q_header + where_feat[i]
q_final= q_header + q_foot
pretty_res = {}
for row in rdf_graph.query(q_final):
x = str(row).split("'")[1]
y = x.split("/")[3]
results.append(y)
if len(results) == 1:
print(results[0])
response = "1 Artigo Encontrado:\n"+"ID: "+results[0] + ""
elif len(results) == 0:
response = "Nenhum Artigo Encontrado :(\n"
else:
response = "Vários Artigos Encontrados:\nID's:"
for i in range(len(results)):
response = response + results[i]+"|"
return response
def sparql_query(keywords):
#save_rdf('demo.rdf')
dictx = load_dict('dict_pred_obj.txt')
# print(dictx)
rdf_graph = load_rdf('KDB.rdf')
# print(rdf_graph)
success = 0
##SEARCH FOR SIMILARITY IN THE DICT OF PREDICATES AND OBJECTS
query_dict = {}
for k in keywords:
for key,values in dictx.items():
if k in values:
query_dict[key]=k
if(len(query_dict.keys()) > 0):
success = 1
response = do_sparql_query(query_dict,rdf_graph)
return response
# print(sparql_query(['polo','m',]))