本文整理汇总了Python中rdflib.ConjunctiveGraph类的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph类的具体用法?Python ConjunctiveGraph怎么用?Python ConjunctiveGraph使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConjunctiveGraph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rdf
def test_rdf(mfile):
g = ConjunctiveGraph()
try:
g = g.parse(mfile, format='xml')
return True
except Exception as inst:
return False
示例2: RecursionTests
class RecursionTests(unittest.TestCase):
# debug = True
def setUp(self):
self.graph = ConjunctiveGraph()
self.graph.load(StringIO(testContent), format='n3')
def test_simple_recursion(self):
graph = ConjunctiveGraph()
graph.load(StringIO(BASIC_KNOWS_DATA), format='n3')
results = graph.query(KNOWS_QUERY,
processor="sparql",
DEBUG=False)
results = set(results)
person1 = URIRef('ex:person.1')
person2 = URIRef('ex:person.2')
nose.tools.assert_equal(
results,
set([(person1, None), (person1, Literal('person 3')),
(person2, Literal('person 3'))]))
def test_secondary_recursion(self):
graph = ConjunctiveGraph()
graph.load(StringIO(SUBCLASS_DATA), format='n3')
results = graph.query(SUBCLASS_QUERY,
processor="sparql",
DEBUG=False)
results = set(results)
ob = URIRef('ex:ob')
class1 = URIRef('ex:class.1')
class2 = URIRef('ex:class.2')
class3 = URIRef('ex:class.3')
nose.tools.assert_equal(
results,
set([(ob, class1), (ob, class2), (ob, class3)]))
示例3: fill_graph_by_subject
def fill_graph_by_subject(basegraph, newgraph, subject, loop_count=0):
"""
Fills an Graph with all triples with an certain subject. Includes the necessary triples for the objects until the deepth of 5.
:param basegraph: Graph with the data for the new Graph
:param newgraph: Instance of the new Graph
:param subject: subject of triples which is looked for in the basegraph
:return: Graph
"""
subject_list=[BNode,URIRef]
if not issubclass(type(basegraph),Graph):
log.error("The given basegraph is not a subclass of Graph!")
return ConjunctiveGraph()
elif subject == "":
log.info("The given subject was empty. Returning the basegraph")
return basegraph
elif type(subject) not in subject_list:
log.info("The given subject was not of type BNode or URIRef. Returning the basegraph")
return basegraph
elif not issubclass(type(newgraph),Graph):
newgraph=ConjunctiveGraph()
loop_count += 1
for s, p, o in basegraph.triples((subject, None, None)):
newgraph.add((s, p, o))
if type(o) in subject_list and loop_count < 6: # it will do: (S1,P1,O1) -> if O1 has an own Description: (O1,P2,O2)... 5 times
newgraph = fill_graph_by_subject(basegraph, newgraph, o, loop_count)
return newgraph
示例4: test_flowcells_index_rdfa
def test_flowcells_index_rdfa(self):
model = ConjunctiveGraph()
response = self.client.get(reverse('flowcell_index'))
self.assertEqual(response.status_code, 200)
model.parse(data=smart_text(response.content), format='rdfa')
add_default_schemas(model)
inference = Infer(model)
errmsgs = list(inference.run_validation())
self.assertEqual(len(errmsgs), 0, errmsgs)
body = """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
select ?flowcell
where {
?flowcell a libns:IlluminaFlowcell .
}"""
bindings = set(['flowcell'])
count = 0
for r in model.query(body):
count += 1
self.assertEqual(count, len(FlowCell.objects.all()))
示例5: open
def open(self):
# XXX: If we have a source that's read only, should we need to set the
# store separately??
g0 = ConjunctiveGraph('SPARQLUpdateStore')
g0.open(tuple(self.conf['rdf.store_conf']))
self.graph = g0
return self.graph
示例6: _graphFromQuads2
def _graphFromQuads2(q):
g = ConjunctiveGraph()
#g.addN(q) # no effect on nquad output
for s,p,o,c in q:
g.get_context(c).add((s,p,o)) # kind of works with broken rdflib nquad serializer code
#g.store.add((s,p,o), c) # no effect on nquad output
return g
示例7: describe
def describe(self, s_or_po, initBindings={}, initNs={}):
"""
Executes a SPARQL describe of resource
:param s_or_po: is either
* a subject ... should be a URIRef
* a tuple of (predicate,object) ... pred should be inverse functional
* a describe query string
:param initBindings: A mapping from a Variable to an RDFLib term (used
as initial bindings for SPARQL query)
:param initNs: A mapping from a namespace prefix to a namespace
"""
if isinstance(s_or_po, str):
query = s_or_po
if initNs:
prefixes = ''.join(["prefix %s: <%s>\n" % (p, n)
for p, n in initNs.items()])
query = prefixes + query
elif isinstance(s_or_po, URIRef) or isinstance(s_or_po, BNode):
query = "describe %s" % (s_or_po.n3())
else:
p, o = s_or_po
query = "describe ?s where {?s %s %s}" % (p.n3(), o.n3())
query = dict(query=query)
url = self.url + "?" + urlencode(query)
req = Request(url)
req.add_header('Accept', 'application/rdf+xml')
log.debug("opening url: %s\n with headers: %s" %
(req.get_full_url(), req.header_items()))
subgraph = ConjunctiveGraph()
subgraph.parse(urlopen(req))
return subgraph
示例8: __call__
def __call__(self, url, **kwargs):
if not url:
return []
graph = ConjunctiveGraph()
graph.parse(url)
output = {}
for subject, predicate, context in graph:
key = self.strip(subject)
prop = self.strip(predicate)
value = self.defrag(context)
output.setdefault(key, {
'label': key,
'uri': unicode(subject)
})
if prop in output[key]:
old = output[key][prop]
if not isinstance(old, list):
output[key][prop] = [old]
output[key][prop].append(value)
else:
output[key][prop] = value
return output.values()
示例9: _test_serializer
def _test_serializer(inputpath, expectedpath, context, serpar):
test_tree, test_graph = _load_test_data(inputpath, expectedpath, context)
if isinstance(test_tree, ConjunctiveGraph):
expected = test_tree.serialize(format="json-ld")
else:
expected = _to_json(_to_ordered(test_tree))
if test_graph is not None:
# toRdf, expected are nquads
result_tree = to_tree(test_graph, context_data=context)
result = _to_json(_to_ordered(result_tree))
elif inputpath.startswith('fromRdf'):
# fromRdf, expected in json-ld
g = ConjunctiveGraph()
data = open(p.join(test_dir, inputpath), 'rb').read()
g.parse(data=data, format="nquads", context=context)
result = g.serialize(format="json-ld", base=context)
else:
# json
f = open(p.join(test_dir, inputpath), 'rb')
result = json.load(f)[0]
f.close()
if isinstance(result, ConjunctiveGraph):
assert isomorphic(result, expected), \
"Expected graph of %s:\n%s\nGot graph of %s:\n %s" % (
expected.serialize(format='n3'),
result.serialize(format='n3'))
else:
assert jsonld_compare(expected, result) == True, \
"Expected JSON:\n%s\nGot:\n%s" % (expected, result)
示例10: ConvertToRDFN3
def ConvertToRDFN3 (filename, destinationFileName):
_graph = ConjunctiveGraph()
_graph.parse(filename, format="nt")
of = open(destinationFileName, "wb")
of.write(_graph.serialize(format="n3"))
of.close()
示例11: discussion_as_graph
def discussion_as_graph(self, discussion_id):
self.ensure_discussion_storage(None)
from assembl.models import Discussion
d_storage_name = self.discussion_storage_name()
d_graph_iri = URIRef(self.discussion_graph_iri())
v = get_virtuoso(self.session, d_storage_name)
discussion_uri = URIRef(
Discussion.uri_generic(discussion_id, self.local_uri()))
subjects = list(v.query(
"""SELECT DISTINCT ?s WHERE {
?s assembl:in_conversation %s }""" % (discussion_uri.n3())))
subjects.append([discussion_uri])
# print len(subjects)
cg = ConjunctiveGraph(identifier=d_graph_iri)
for (s,) in subjects:
# Absurdly slow. DISTINCT speeds up a lot, but I get numbers.
for p, o in v.query(
'SELECT ?p ?o WHERE { graph %s { %s ?p ?o }}' % (
d_graph_iri.n3(), s.n3())):
cg.add((s, p, o))
for (s, o, g) in v.query(
'''SELECT ?s ?o ?g WHERE {
GRAPH ?g {?s catalyst:expressesIdea ?o } .
?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
cg.add((s, CATALYST.expressesIdea, o, g))
# TODO: Add roles
return cg
示例12: validate_sparql_endpoint
def validate_sparql_endpoint(form, field):
try:
g = ConjunctiveGraph('SPARQLStore')
g.open(field.data)
g.query('SELECT * WHERE { ?s ?p ?o } LIMIT 1')
except:
raise ValidationError('This is not a valid SPARQL endpoint.')
示例13: __init__
def __init__(self, store=None, id=None):
if store is not None and id is not None:
ConjunctiveGraph.__init__(self, store, id)
else:
ConjunctiveGraph.__init__(self)
for (key,val) in namespaces.iteritems():
self.bind(key, val)
示例14: construct
def construct(self, strOrTriple, initBindings={}, initNs={}):
"""
Executes a SPARQL Construct
:param strOrTriple: can be either
* a string in which case it it considered a CONSTRUCT query
* a triple in which case it acts as the rdflib `triples((s,p,o))`
:param initBindings: A mapping from a Variable to an RDFLib term (used as initial bindings for SPARQL query)
:param initNs: A mapping from a namespace prefix to a namespace
:returns: an instance of rdflib.ConjuctiveGraph('IOMemory')
"""
if isinstance(strOrTriple, str):
query = strOrTriple
if initNs:
prefixes = ''.join(["prefix %s: <%s>\n"%(p,n) for p,n in initNs.items()])
query = prefixes + query
else:
s,p,o = strOrTriple
t='%s %s %s'%((s and s.n3() or '?s'),(p and p.n3() or '?p'),(o and o.n3() or '?o'))
query='construct {%s} where {%s}'%(t,t)
query = dict(query=query)
url = self.url+"?"+urlencode(query)
req = Request(url)
req.add_header('Accept','application/rdf+xml')
log.debug("Request url: %s\n with headers: %s" % (req.get_full_url(), req.header_items()))
subgraph = ConjunctiveGraph('IOMemory')
subgraph.parse(urlopen(req))
return subgraph
示例15: _construct
def _construct(compiler, sources, query=None):
dataset = ConjunctiveGraph()
if not isinstance(sources, list):
sources = [sources]
for sourcedfn in sources:
source = sourcedfn['source']
graph = dataset.get_context(URIRef(sourcedfn.get('dataset') or source))
if isinstance(source, (dict, list)):
context_data = sourcedfn['context']
if not isinstance(context_data, list):
context_data = compiler.load_json(context_data )['@context']
context_data = [compiler.load_json(ctx)['@context']
if isinstance(ctx, unicode) else ctx
for ctx in context_data]
to_rdf(source, graph, context_data=context_data)
elif isinstance(source, Graph):
graph += source
else:
graph += compiler.cached_rdf(source)
if not query:
return graph
with compiler.path(query).open() as fp:
result = dataset.query(fp.read())
g = Graph()
for spo in result:
g.add(spo)
return g