Ata*_*man 4 python rdf ontology sparql
我有以下Python代码.它基本上使用SPARQL从在线资源返回RDF的一些元素.
我想查询并从我的本地文件中返回一些内容.我试图编辑它但无法返回任何内容.
为了在我的本地而不是http://dbpedia.org/resource中查询,我应该更改什么?
from SPARQLWrapper import SPARQLWrapper, JSON
# wrap the dbpedia SPARQL end-point
endpoint = SPARQLWrapper("http://dbpedia.org/sparql")
# set the query string
endpoint.setQuery("""
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpr: <http://dbpedia.org/resource/>
SELECT ?label
WHERE { dbpr:Asturias rdfs:label ?label }
""")
# select the retur format (e.g. XML, JSON etc...)
endpoint.setReturnFormat(JSON)
# execute the query and convert into Python objects
# Note: The JSON returned by the SPARQL endpoint is converted to nested Python dictionaries, so additional parsing is not required.
results = endpoint.query().convert()
# interpret the results:
for res in results["results"]["bindings"] :
print res['label']['value']
Run Code Online (Sandbox Code Playgroud)
谢谢!
SPARQLWrapper
仅用于远程或本地SPARQL端点。您有两种选择:
(a)将本地RDF文件放在本地三元组存储中,然后将代码指向localhost。(b)或使用rdflib
和使用InMemory
储存器:
import rdflib.graph as g
graph = g.Graph()
graph.parse('filename.rdf', format='rdf')
print graph.serialize(format='pretty-xml')
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令查询rdflib.graph.Graph():
filename = "path/to/fileneme" #replace with something interesting
uri = "uri_of_interest" #replace with something interesting
import rdflib
import rdfextras
rdfextras.registerplugins() # so we can Graph.query()
g=rdflib.Graph()
g.parse(filename)
results = g.query("""
SELECT ?p ?o
WHERE {
<%s> ?p ?o.
}
ORDER BY (?p)
""" % uri) #get every predicate and object about the uri
Run Code Online (Sandbox Code Playgroud)