-
Notifications
You must be signed in to change notification settings - Fork 572
/
Copy pathtest_subselectOptional.py
97 lines (68 loc) · 2.2 KB
/
test_subselectOptional.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
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 18:21:28 2024
See issue https://github.com/RDFLib/rdflib/issues/2957.
@author: Administrator
"""
from rdflib import Graph, Literal, URIRef, Variable
import os
current_dir = os.getcwd()
GraphString = '''
prefix ex: <https://www.example.org/>
ex:document ex:subject "Nice cars" .
ex:document ex:theme "Car" .
'''
someGraph = Graph()
someGraph.parse(data=GraphString , format="turtle")
# This query states first a normal triple pattern and then an optional clause with a subselect query.
Query1 = someGraph.query('''
prefix ex: <https://www.example.org/>
select ?subject ?theme
where {
?doc1 ex:subject ?subject.
OPTIONAL
{
select ?theme
where {
?doc1 ex:theme ?theme.
}
}
}
''')
filepath = current_dir+"/output1.txt"
# Print the results with variable names and their bindings
print ('\nResults for Query1: \n')
for row in Query1:
print ("Result 'subject: "+ str(row.subject) + "'\nResult should show 'subject: Nice cars' \n")
print ("Result 'theme: " + str(row.theme) + "'\nResult should show 'theme: Car'")
with open(filepath, 'w', encoding='utf-8') as file:
file.write(str(row))
# Result should yield two rows:
# subject: Nice cars
# theme: Car
# This query states first an optional clause with a subselect query and then a normal triple pattern.
Query2 = someGraph.query('''
prefix ex: <https://www.example.org/>
select ?subject ?theme
where {
OPTIONAL
{
select ?theme
where {
?doc1 ex:theme ?theme.
}
}
?doc1 ex:subject ?subject.
}
''')
filepath = current_dir+"/output2.txt"
# Print the results with variable names and their bindings
print ('\nResults for Query2: \n')
for row in Query2:
print ("Result 'subject: "+ str(row.subject) + "'\nResult should show 'subject: Nice cars' \n")
print ("Result 'theme: " + str(row.theme) + "'\nResult should show 'theme: Car'")
with open(filepath, 'w', encoding='utf-8') as file:
file.write(str(row))
# Result should yield two rows:
# subject: Nice cars
# theme: Car