Python Sparql Querying Local File
Asked Answered
I

2

7

I have the following Python code. It basically returns some elements of RDF from an online resource using SPARQL.

I want to query and return something from one of my local files. I tried to edit it but couldn't return anything.

What should I change in order to query within my local instead of 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']

Thanks!

Isleen answered 26/3, 2012 at 18:54 Comment(0)
I
6

SPARQLWrapper is meant to be used only with remote or local SPARQL endpoints. You have two options:

(a) Put your local RDF file in a local triple store and point your code to localhost. (b) Or use rdflib and use the InMemory storage:

import rdflib.graph as g
graph = g.Graph()
graph.parse('filename.rdf', format='rdf')
print graph.serialize(format='pretty-xml')
Immanent answered 27/3, 2012 at 0:50 Comment(0)
P
6

You can query the rdflib.graph.Graph() with:

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
Petua answered 6/6, 2012 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.