Skip to content

Instantly share code, notes, and snippets.

@tatiana
Created June 21, 2012 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatiana/2967837 to your computer and use it in GitHub Desktop.
Save tatiana/2967837 to your computer and use it in GitHub Desktop.
First steps with RDFAlchemy and SPARQL to access DBPedia
from rdfalchemy.sparql import SPARQLGraph
from rdflib import Namespace
query = """
PREFIX db: <http://dbpedia.org/resource/>
PREFIX dbonto: <http://dbpedia.org/ontology/>
SELECT DISTINCT ?who
FROM <http://dbpedia.org>
WHERE {
?who dbonto:genre db:Metal .
}
"""
endpoint = "http://dbpedia.org/sparql"
graph = SPARQLGraph(endpoint)
# Option 1: Running raw query
metal_guys1 = list(graph.query(query, resultMethod='xml'))
print u"Number of things with genre Metal", len(metal_guys1)
# output: 43
# Option 2: Calling using namespaces and subjects
DB = Namespace('http://dbpedia.org/resource/')
DBONTO = Namespace("http://dbpedia.org/ontology/")
metal_guys2 = list(graph.subjects(predicate=DB.genre, object=DBONTO.Metal))
print u"Number of things with genre Metal", len(metal_guys2)
# output: 0
assert metal_guys1 == metal_guys2
# :( AssertionError
@tatiana
Copy link
Author

tatiana commented Jun 22, 2012

This code has a problem. Line 28 should be:

metal_guys2 = list(graph.subjects(predicate=DBONTO.genre, object=DB.Metal))

Also, it is needed to sort the lists before the assert, on line 32.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment