Query an RDF graph


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #### notes:
  2. ## in order to make the sparql query work with the literals, I modified all the rdf source files!!!
  3. ## they had the <rdf:datatype="http://www.w3.org/2001/XMLSchema#string"> datatype, I just replaced it with an unnamed literal
  4.  
  5. import rdflib
  6.  
  7.  
  8. from rdflib.Graph import Graph
  9. from rdflib import Namespace
  10.  
  11. g = Graph()
  12.  
  13. myfile ='/Users/mac/Documents/Ontologies/sentence_instances_8_12_08.owl'
  14.  
  15. g.parse(myfile, format="xml")
  16. print "the lenght of the graph is: ", len(g)
  17.  
  18.  
  19.  
  20. result = g.query("""PREFIX phil: <http://myontology.owl/>
  21. PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
  22. SELECT ?x ?p
  23. WHERE { ?s phil:HAS-NUMBER-REFERENCE ?p . ?s phil:HAS-STRING-CONTENT ?x . } """
  24. )
  25.  
  26.  
  27. print "Query result: ", len(result)
  28.  
  29. dict = {}
  30.  
  31. #serialize the results
  32. for r in result.serialize('python'):
  33. dict[r[1].__str__()] = r[0].__str__()
  34.  
  35.  
  36. print "The dictionary has collapsed %s total sentences into %s elements" % (len(result), len(dict.keys()))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.