Created
June 21, 2012 19:02
-
-
Save tatiana/2967837 to your computer and use it in GitHub Desktop.
First steps with RDFAlchemy and SPARQL to access DBPedia
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code has a problem. Line 28 should be:
Also, it is needed to sort the lists before the assert, on line 32.