-
Notifications
You must be signed in to change notification settings - Fork 1
/
query.py
66 lines (57 loc) · 2.82 KB
/
query.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
from rdflib import Graph
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("graphpath")
parser.add_argument("sqlout")
parser.add_argument("--subj")
parser.add_argument("--pred")
args = parser.parse_args()
store = Graph()
store.load(args.graphpath)
with open(args.sqlout, "w", encoding='utf-8') as file:
if args.subj and args.pred:
query = 'SELECT ?subj_words ?pred_words ?obj_words ' \
'WHERE { ?relation relation:subject ?subj .' \
' ?subj entity:words ?subj_words .' \
'' \
' ?relation relation:predicate ?pred_words .' \
'' \
' ?relation relation:object ?obj .' \
' ?obj entity:words ?obj_words .' \
'FILTER ( regex( ?subj_words, "' + args.subj + '") && ' \
' regex( ?pred_words, "' + args.pred + '") ) }' \
for row in store.query(query):
file.write("Subject: {}\nPredicate: {}\nObject: {}\n\n".format(
row.subj_words, row.pred_words, row.obj_words
))
elif args.subj:
query = 'SELECT ?subj_words ?pred_words ?obj_words ' \
'WHERE { ?relation relation:subject ?subj .' \
' ?subj entity:words ?subj_words .' \
'' \
' ?relation relation:predicate ?pred_words .' \
'' \
' ?relation relation:object ?obj .' \
' ?obj entity:words ?obj_words .' \
'FILTER ( regex( ?subj_words, "' + args.subj + '")) }' \
for row in store.query(query):
file.write("Subject: {}\nPredicate: {}\nObject: {}\n\n".format(
row.subj_words, row.pred_words, row.obj_words
))
elif args.pred:
query = 'SELECT ?subj_words ?pred_words ?obj_words ' \
'WHERE { ?relation relation:subject ?subj .' \
' ?subj entity:words ?subj_words .' \
'' \
' ?relation relation:predicate ?pred_words .' \
'' \
' ?relation relation:object ?obj .' \
' ?obj entity:words ?obj_words .' \
'FILTER ( regex( ?pred_words, "' + args.pred + '")) }' \
for row in store.query(query):
file.write("Subject: {}\nPredicate: {}\nObject: {}\n\n".format(
row.subj_words, row.pred_words, row.obj_words
))
else:
raise ValueError("Your must specify either the subject or relation")