本文整理汇总了Python中rdflib.ConjunctiveGraph.query方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.query方法的具体用法?Python ConjunctiveGraph.query怎么用?Python ConjunctiveGraph.query使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_sparql_endpoint
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
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.')
示例2: __init__
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def __init__(self, raw_result):
rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
c = Namespace("http://s.opencalais.com/1/pred/")
g = Graph()
self.graph = g
g.parse(StringIO(raw_result.decode('utf-8').encode('utf-8')))
self.categories = [row for row in g.query(CATEGORY_QUERY["SPARQL"])]
self.entities = [row for row in g.query(ENTITY_QUERY["SPARQL"])]
示例3: FOAF
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class FOAF(callbacks.Privmsg):
DATAFILE = "/var/www/rc98.net/zoia.rdf"
def __init__(self, irc):
self.g = Graph()
# self.g.parse('http://rc98.net/zoia.rdf')
self.g.parse(self.DATAFILE, format="xml")
self.uri = rdflib.URIRef("http://www.code4lib.org/id/zoia")
self.FOAF = Namespace("http://xmlns.com/foaf/0.1/")
super(callbacks.Plugin, self).__init__(irc)
def _uri_of_user(self, nick):
result = self.g.query(
"""
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?uri WHERE
{<http://www.code4lib.org/id/zoia> foaf:knows ?uri . ?uri foaf:nick ?nick .}
""",
initBindings={"nick": nick},
)
if len(result) > 0:
userURI = list(result)[0][0]
return userURI
else:
return None
def _user_graph(self, uri):
userGraph = Graph()
try:
userGraph.parse(uri)
except Exception, e:
u = "http://www.w3.org/2007/08/pyRdfa/extract?space-preserve=true&uri=" + uri
userGraph.parse(u, identifier=uri)
return userGraph
示例4: get_all_measurement_types
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def get_all_measurement_types(ontology_file):
graph = ConjunctiveGraph()
graph.load(ontology_file, format="n3")
query_str = '''SELECT DISTINCT ?mt ?label ?comment ?defn
WHERE {
?mt rdfs:label ?label .
?mt rdfs:subClassOf <%s> .
?mt rdfs:subClassOf ?r1 .
?r1 owl:onProperty oboe:measuresEntity ; owl:someValuesFrom ?ent .
?mt rdfs:subClassOf ?r2 .
?r2 owl:onProperty oboe:measuresCharacteristic ; owl:someValuesFrom ?char .
OPTIONAL { ?mt rdfs:comment ?comment }
OPTIONAL { ?mt skos:definition ?defn }
}''' % (MeasurementType)
qres = list(graph.query(query_str, initNs=dict(oboe=URIRef("http://ecoinformatics.org/oboe/oboe.1.2/oboe-core.owl#"),
owl=OWL,rdfs=RDFS,skos=SKOS)))
if len(qres) > 0:
qres.sort(key=lambda x: x[0], reverse=True)
result = dict()
i = 0
for row in qres:
result[i] = {'uri' : row[0], 'label' : row[1], 'comment' : row[2], 'defn' : row[3]}
i = i + 1
print "Sparql query finished!"
return result
return None
示例5: test_dSet_parsed_as_context_returns_results
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def test_dSet_parsed_as_context_returns_results(self):
querystr = """SELECT DISTINCT ?s FROM <http://test/> { ?s ?p ?o }"""
graph = ConjunctiveGraph()
graph.get_context(URIRef('http://test/')
).parse("http://www.w3.org/People/Berners-Lee/card.rdf")
r = graph.query(querystr, loadContexts=True)
self.assert_(len(r.bindings) is not 0)
示例6: _construct
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
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
示例7: test_flowcells_index_rdfa
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
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()))
示例8: Config
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class Config(object):
def __init__(self, masterGraph, hubHost):
self.etcd = etcd3.client(host=hubHost, port=9022)
self.masterGraph = masterGraph
self.hubHost = hubHost
self.configGraph = ConjunctiveGraph()
self.boards = []
self.etcPrefix = 'pi/'
self.reread()
deferToThread(self.watchEtcd)
def watchEtcd(self):
events, cancel = self.etcd.watch_prefix(self.etcPrefix)
reactor.addSystemEventTrigger('before', 'shutdown', cancel)
for ev in events:
log.info('%s changed', ev.key)
reactor.callFromThread(self.configChanged)
def configChanged(self):
self.cancelRead()
self.rereadLater = reactor.callLater(.1, self.reread)
def cancelRead(self):
if getattr(self, 'rereadLater', None):
self.rereadLater.cancel()
self.rereadLater = None
@STATS.configReread.time()
def reread(self):
self.rereadLater = None
log.info('read config')
self.configGraph = ConjunctiveGraph()
for v, md in self.etcd.get_prefix(self.etcPrefix):
log.info(' read file %r', md.key)
self.configGraph.parse(StringInputSource(v), format='n3')
self.configGraph.bind('', ROOM)
self.configGraph.bind('rdf', RDF)
# config graph is too noisy; maybe make it a separate resource
#masterGraph.patch(Patch(addGraph=self.configGraph))
self.setupBoards()
def setupBoards(self):
thisHost = Literal(hostname)
for row in self.configGraph.query(
'SELECT ?board WHERE { ?board a :PiBoard; :hostname ?h }',
initBindings=dict(h=thisHost)):
thisBoard = row.board
break
else:
log.warn("config had no board for :hostname %s. Waiting for config update." %
thisHost)
self.boards = []
return
log.info("found config for board %r" % thisBoard)
self.boards = [Board(self.configGraph, self.masterGraph, thisBoard, self.hubHost)]
self.boards[0].startPolling()
示例9: TestSparqlJsonResults
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class TestSparqlJsonResults(unittest.TestCase):
def setUp(self):
self.graph = ConjunctiveGraph()
self.graph.parse(StringIO(test_data), format="n3")
def test_base_ref(self):
rt=self.graph.query(test_query).serialize("python")
self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)
示例10: runTest
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def runTest(self):
"""Run the specified task force test."""
import rdfadict
import rdfadict.sink.graph
print self._uri
# set up our target sink
g = Graph()
sink = rdfadict.sink.graph.GraphSink(g)
# run rdfadict over the input
parser = rdfadict.RdfaParser()
parser.parseurl(self._source, sink)
# execute the test SPARQL
g.query(self._result)
print g.selected
示例11: TestSparqlOPT_FILTER2
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class TestSparqlOPT_FILTER2(unittest.TestCase):
def setUp(self):
self.graph = ConjunctiveGraph()
self.graph.load(StringIO(testContent), format='n3')
def test_OPT_FILTER(self):
results = self.graph.query(QUERY,
DEBUG=False)
results = list(results)
self.failUnless(
results == [(doc1,)],
"expecting : %s . Got: %s"%([(doc1,)],repr(results)))
示例12: test_simple_recursion
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
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'))]))
示例13: TestSPARQLFilters
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class TestSPARQLFilters(unittest.TestCase):
debug = False
sparql = True
def setUp(self):
NS = u"http://example.org/"
self.graph = ConjunctiveGraph()
self.graph.parse(data=testgraph, format="n3", publicID=NS)
def testSPARQLNotEquals(self):
rt = self.graph.query(testquery, initNs={'rdf': RDF.uri}, DEBUG=False)
for row in rt:
assert str(row[0]) == "http://example.org/bar" #, "unexpected item of '%s'" % repr(row[0])
示例14: JSON
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class JSON(unittest.TestCase):
def setUp(self):
self.graph = ConjunctiveGraph(plugin.get('IOMemory',Store)())
self.graph.parse(StringIO(test_data), format="n3")
def testComma(self):
"""
Verify the serialisation of the data as json contains an exact
substring, with the comma in the correct place.
"""
results = self.graph.query(test_query)
result_json = results.serialize(format='json')
self.failUnless(result_json.find(correct) > 0)
def testHeader(self):
"""
Verify that the "x", substring is omitted from the serialised output.
"""
results = self.graph.query(test_header_query)
result_json = results.serialize(format='json')
self.failUnless(result_json.find('"x",') == -1)
示例15: _DBPediaMixin
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class _DBPediaMixin(object):
def __init__(self):
self.graph = ConjunctiveGraph('SPARQLStore')
def _get_media_api_host(self, language):
return language + u'.wikipedia.org'
def _get_dbpedia_url(self, language):
return u'http://' +('' if language == u'en' else language + u'.') + u'dbpedia.org'
def _fetch_dbpedia_query_result(self, query):
result = self.graph.query( unicode(query) )
return_fetch_results = [ [ unicode(e.n3()) if (not e is None) else '' for e in fetch_result] for fetch_result in result ]
return return_fetch_results