本文整理汇总了Python中rdflib.plugins.sparql.prepareQuery函数的典型用法代码示例。如果您正苦于以下问题:Python prepareQuery函数的具体用法?Python prepareQuery怎么用?Python prepareQuery使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了prepareQuery函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rewriteQueryToCapabilityMap
def rewriteQueryToCapabilityMap(q):
# Note, for debugging, use: algebra.pprintAlgebra(<node?>)
# Navigate to BGP node in tree
prologue_ = []
for prefix, uri in q.prologue.namespace_manager.namespaces():
prologue_.append("PREFIX %s: <%s>" % (prefix, uri,))
capabilityServiceMappings = [ ('http://froogle.com/', algebra.Join( algebra.BGP([( Variable('a'), Variable('a'), Variable('a'))]), algebra.BGP([( Variable('b'), Variable('b'), Variable('b'))]))), ]
addServiceCapabilities(q.algebra, capabilityServiceMappings)
query_ = evalPart(q.prologue, q.algebra)
#print "\n".join(prologue_)
print query_
# ServiceGraphPattern(
# term = http://fish.db.endpoint
# graph = GroupGraphPatternSub(
# part = [TriplesBlock_{'_vars': set([?dbp]), 'triples': [[?dbp, rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.Literal(u'fish')]]}]
# _vars = set([?dbp])
# )
# _vars = set([?dbp])
# )
try:
prepareQuery("\n".join(prologue_) + query_, initNs = initNS)
except:
print '## Did not validate ##'
示例2: parse
def parse(foaf_url):
global gexf_graph
global parsedFOAFS
global queuedFOAFS
g = Graph()
try:
g.load(foaf_url)
except Exception:
print "Can't fetch " + foaf_url
return
SIOC = Namespace("http://rdfs.org/sioc/ns#")
acctID = URIRef(g.value(URIRef(foaf_url), FOAF.maker) + "#acct")
root_accountName = str(g.value(acctID, FOAF.accountName))
root_webfinger = root_accountName + "@" + urlparse(foaf_url).hostname
subscriptions = prepareQuery(
"""SELECT ?accountName ?accountProfilePage
WHERE {
?person sioc:follows ?b .
?b foaf:accountName ?accountName .
?b foaf:accountProfilePage ?accountProfilePage .
}""",
initNs = { "foaf": FOAF, "sioc": SIOC })
subscribers = prepareQuery(
"""SELECT ?accountName ?accountProfilePage
WHERE {
?b sioc:follows ?person .
?b foaf:accountName ?accountName .
?b foaf:accountProfilePage ?accountProfilePage .
}""",
initNs = { "foaf": FOAF, "sioc": SIOC })
gexf_graph.addNode(root_webfinger, root_webfinger)
for subscription in g.query(subscriptions, initBindings={'person': acctID}):
accountProfilePage = str(subscription.accountProfilePage) + "/foaf"
accountName = str(subscription.accountName)
if (blacklisted(accountProfilePage) is False):
hostname = urlparse(accountProfilePage).hostname
webfinger = accountName + "@" + hostname
gexf_graph.addNode(webfinger, webfinger)
gexf_graph.addEdge(root_webfinger + webfinger, root_webfinger, webfinger)
if accountProfilePage not in parsedFOAFS:
queuedFOAFS.put(accountProfilePage)
for subscriber in g.query(subscribers, initBindings={'person': acctID}):
accountProfilePage = str(subscriber.accountProfilePage) + "/foaf"
accountName = str(subscriber.accountName)
if (blacklisted(accountProfilePage) is False):
hostname = urlparse(accountProfilePage).hostname
webfinger = accountName + "@" + hostname
gexf_graph.addNode(webfinger, webfinger)
gexf_graph.addEdge(webfinger + root_webfinger, root_webfinger, webfinger)
if accountProfilePage not in parsedFOAFS:
queuedFOAFS.put(accountProfilePage)
示例3: find_filenames_for_tags
def find_filenames_for_tags(self, tags, flag_only_existing=False):
dinst_set = self.find_datainstances_for_tags(tags)
print(dinst_set)
g = Graph()
for dinst in dinst_set:
g.parse(self.client.target('observation/data-about?urn=' + dinst))
filepaths = {}
for dinst in dinst_set:
queryDataInstance = prepareQuery("""
SELECT DISTINCT ?filepath ?dataobject
WHERE {
?dataInstance fff:dataObject ?dataobject .
?dataInstance fff:dataLocation ?dataLocation .
?dataLocation fff:filePath ?filepath .
}""", initNs=ns)
queryDataObject = prepareQuery(
"""
SELECT ?tag
WHERE {
?anno oa:hasTarget ?dataobject .
?anno oa:hasBody ?body .
?body cnt:chars ?tag .
}""", initNs=ns)
queryDataInstance
dinst_uri = URIRef(dinst)
filepath = ""
tags = set()
for row in g.query(queryDataInstance, initBindings=dict(dataInstance=dinst_uri)):
try:
row['filepath']
fp = row['filepath'].value
filepath = fp
print fp
except KeyError:
pass
try:
dataobject = "" + row['dataobject']
g.parse(self.client.target("observation/data-about?urn=" + dataobject))
# print len(g)
for row2 in g.query(queryDataObject, initBindings=dict(dataobject=dataobject)):
try:
row2['tag']
tag = row2['tag'].value
tags.add(tag)
except KeyError:
pass
except KeyError:
pass
# if (flag_only_existing and os.path.exists(filepath)):
# filepaths[filepath] = tags
# else:
filepaths[filepath] = tags
return filepaths
示例4: add_prepared_query
def add_prepared_query(self, name, query, initNs=None):
self.log.debug("adding prepared query with name %s", name)
pq = lambda x,y: prepareQuery(x, initNs=y)
if initNs is None:
pq = lambda x,y: prepareQuery(x)
prepared_query = pq(query, initNs)
self.prepared_queries[name] = (query, prepared_query)
self.prepared_query_to_str[prepared_query] = query
return self.prepared_queries[name][-1]
示例5: __init__
def __init__(self, callback, sparql_query):
"""Creates a SPARQL filter for RDF triples."""
if sparql_query.strip()[:3].lower() != 'ask':
raise ZtreamyException('Only ASK queries are allowed '
'in SPARQLFilter')
super(SPARQLFilter, self).__init__(callback)
self.query = prepareQuery(sparql_query)
示例6: test_dataset_description_linksets
def test_dataset_description_linksets(self):
res = self.client.get('/.well-known/void')
self.assertEqual(res.status_code, http.client.OK)
self.assertEqual(res.headers['Content-Type'], 'text/turtle')
g = Graph()
g.parse(format='turtle', data=res.get_data(as_text=True))
# http://dbpedia.org/void/Dataset
q = sparql.prepareQuery('''
SELECT ?triples
WHERE {
?linkset a void:Linkset .
?linkset void:subset <http://n2t.net/ark:/99152/p0d> .
?linkset void:subjectsTarget <http://n2t.net/ark:/99152/p0d> .
?linkset void:linkPredicate ?predicate .
?linkset void:objectsTarget ?dataset .
?linkset void:triples ?triples .
}
''', initNs={'void': VOID})
dbpedia = URIRef('http://dbpedia.org/void/Dataset')
triples = next(iter(g.query(
q, initBindings={'dataset': dbpedia,
'predicate': DCTERMS.spatial})))['triples'].value
self.assertEqual(triples, 3)
worldcat = URIRef('http://purl.oclc.org/dataset/WorldCat')
triples = next(iter(g.query(
q, initBindings={'dataset': worldcat,
'predicate': DCTERMS.isPartOf})))['triples'].value
self.assertEqual(triples, 1)
示例7: loadFragmentDefinitions
def loadFragmentDefinitions(self, folder, fileName):
datasets = {}
self.fragments = {}
with open (fileName, 'r') as f:
for line in f:
line = line.strip()
ws = line.split()
if (len(ws) > 0):
fragment = ws[0]
ds = ws[1]
datasets[fragment] = ds
content = os.listdir(folder)
self.viewsDefinition = {}
for g in content:
path = folder+'/'+g
f = open(path)
viewStr = f.read()
f.close()
view = prepareQuery(viewStr)
t = getTriple(view)
i = path.rfind('/') + 1
j = path.rfind('.')
j = len(path) if j < 0 else j
name = path[i:j]
ds = datasets[name]
self.fragments[name] = TriplePatternFragment(t, ds)
示例8: test_graph_prefix
def test_graph_prefix():
"""
This is issue https://github.com/RDFLib/rdflib/issues/313
"""
g1 = Graph()
g1.parse(data="""
@prefix : <urn:ns1:> .
:foo <p> 42.
""", format="n3")
g2 = Graph()
g2.parse(data="""
@prefix : <urn:somethingelse:> .
<urn:ns1:foo> <p> 42.
""", format="n3")
assert isomorphic(g1, g2)
q_str = ("""
PREFIX : <urn:ns1:>
SELECT ?val
WHERE { :foo ?p ?val }
""")
q_prepared = prepareQuery(q_str)
expected = [(Literal(42),)]
eq_(list(g1.query(q_prepared)), expected)
eq_(list(g2.query(q_prepared)), expected)
eq_(list(g1.query(q_str)), expected)
eq_(list(g2.query(q_str)), expected)
示例9: testQuery
def testQuery():
g = makeGraph()
q = sparql.prepareQuery('SELECT ?o WHERE {?s schema:name ?o} LIMIT 20', initNs = { "schema": "http://schema.org/" })
myquery = g.query(q)
return myquery
示例10: validateSparql
def validateSparql(self, text):
''' validates a sparql query and stores it in a separate file '''
text = str(text)
try:
return sparql.prepareQuery(text, initNs=self.namespaces)
except Exception as error:
raise MalformedSparqlQueryError([str(type(error)), str(error), text])
示例11: timequery
def timequery(action): #time query function
q = prepareQuery(
'SELECT ?time WHERE { ?action alfred:takes ?time .}',
initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
this = parse + action
for row in g.query(q, initBindings={'action': this}):
return int(row.time)
示例12: taskquery
def taskquery(action, tasks=[]): #tasks query function
q = prepareQuery(
'SELECT ?name WHERE { ?action alfred:involves ?task . ?task alfred:named ?name .}',
initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
this = parse + action
for row in g.query(q, initBindings={'action': this}):
print row.name
示例13: moodquery
def moodquery(action): #mood query function
q = prepareQuery(
'SELECT ?name WHERE { ?action alfred:results ?mood . ?mood alfred:named ?name .}',
initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
this = parse + action
for row in g.query(q, initBindings={'action': this}):
return str(row.name)
示例14: test_dataset_description
def test_dataset_description(self):
res1 = self.client.get(
'/', headers={'Accept': 'text/html'}, buffered=True)
self.assertEqual(res1.status_code, http.client.SEE_OTHER)
self.assertEqual(urlparse(res1.headers['Location']).path,
'/index.json.html')
res2 = self.client.get('/', headers={'Accept': 'text/turtle'})
self.assertEqual(res2.status_code, http.client.OK)
self.assertEqual(res2.headers['Content-Type'], 'text/turtle')
res3 = self.client.get('/.well-known/void')
self.assertEqual(res3.status_code, http.client.OK)
self.assertEqual(res3.headers['Content-Type'], 'text/turtle')
self.assertEqual(res3.get_data(as_text=True),
res2.get_data(as_text=True))
res4 = self.client.get('/.wellknown/void')
self.assertEqual(res4.status_code, http.client.OK)
self.assertEqual(res4.headers['Content-Type'], 'text/turtle')
self.assertEqual(res4.get_data(as_text=True),
res3.get_data(as_text=True))
res5 = self.client.get('/.well-known/void.ttl')
self.assertEqual(res5.status_code, http.client.OK)
self.assertEqual(res5.headers['Content-Type'], 'text/turtle')
self.assertEqual(res5.get_data(as_text=True),
res4.get_data(as_text=True))
res6 = self.client.get('/.well-known/void.ttl.html')
self.assertEqual(res6.status_code, http.client.OK)
self.assertEqual(res6.headers['Content-Type'], 'text/html')
g = Graph()
g.parse(format='turtle', data=res2.get_data(as_text=True))
self.assertIn(
(PERIODO['p0d'], DCTERMS.provenance, HOST['h#changes']), g)
desc = g.value(predicate=RDF.type, object=VOID.DatasetDescription)
self.assertEqual(
desc.n3(), '<http://n2t.net/ark:/99152/p0>')
title = g.value(subject=desc, predicate=DCTERMS.title)
self.assertEqual(
title.n3(), '"Description of the PeriodO Period Gazetteer"@en')
q = sparql.prepareQuery('''
SELECT ?count
WHERE {
?d void:classPartition ?p .
?p void:class ?class .
?p void:entities ?count .
}
''', initNs={'void': VOID, 'skos': SKOS})
concept_count = next(iter(g.query(
q, initBindings={'class': SKOS.Concept})))['count'].value
self.assertEqual(concept_count, 3)
scheme_count = next(iter(g.query(
q, initBindings={'class': SKOS.ConceptScheme})))['count'].value
self.assertEqual(scheme_count, 1)
示例15: is_inside
def is_inside(textplace,graph):
"""Returns true if the place defined as text is disambiguated in graph
returns false otherwise"""
askquery = prepareQuery(
"""ASK {?iri schema:jobLocation ?place .
?iri edsa:Location ?placeiri}""",
initNs = {"schema" : ns.schema ,
"edsa" : ns.edsa})
return bool(graph.query(askquery, initBindings={"place" : Literal(textplace)}))