Ataman Ataman - 1 year ago 166
Python Question

Python Sparql Querying Local File

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

from SPARQLWrapper import SPARQLWrapper, JSON

# wrap the dbpedia SPARQL end-point
endpoint = SPARQLWrapper("")

# set the query string
PREFIX rdfs: <>
PREFIX dbpr: <>
SELECT ?label
WHERE { dbpr:Asturias rdfs:label ?label }

# select the retur format (e.g. XML, JSON etc...)

# 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']


Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download