Python Sparql查询本地文件

时间:2012-03-26 18:54:48

标签: python rdf sparql ontology

我有以下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']

谢谢!

2 个答案:

答案 0 :(得分:5)

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')

答案 1 :(得分:5)

您可以使用以下命令查询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