Skip to content

Instantly share code, notes, and snippets.

@colwilson
Created January 19, 2012 22:09
Show Gist options
  • Save colwilson/1643191 to your computer and use it in GitHub Desktop.
Save colwilson/1643191 to your computer and use it in GitHub Desktop.
from SPARQLWrapper import SPARQLWrapper, JSON
class SparqlEndpoint(object):
def __init__(self, endpoint, prefixes={}):
self.sparql = SPARQLWrapper(endpoint)
self.prefixes = {
"dbpedia-owl": "http://dbpedia.org/ontology/",
"owl": "http://www.w3.org/2002/07/owl#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"foaf": "http://xmlns.com/foaf/0.1/",
"dc": "http://purl.org/dc/elements/1.1/",
"dbpedia2": "http://dbpedia.org/property/",
"dbpedia": "http://dbpedia.org/",
"skos": "http://www.w3.org/2004/02/skos/core#",
"foaf": "http://xmlns.com/foaf/0.1/",
}
self.prefixes.update(prefixes)
self.sparql.setReturnFormat(JSON)
def query(self, q):
lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()]
lines.extend(q.split("\n"))
query = "\n".join(lines)
print query
self.sparql.setQuery(query)
results = self.sparql.query().convert()
return results["results"]["bindings"]
class DBpediaEndpoint(SparqlEndpoint):
def __init__(self, prefixes = {}):
endpoint = "http://dbpedia.org/sparql"
super(DBpediaEndpoint, self).__init__(endpoint, prefixes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment