How to parse and load an ontology in Python?

Viewed 5436

I have an ontology in an 'owl' file (nif.owl). I am familiar with Java, but it kept crashing; therefore, I tried using Python. However, since I have not used Python before, I am not sure if I am loading the ontology correctly!

Here is the part that I believe is related to loading the ontology:

g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)

I believe the problem is where the g.parse sets the format to 'xml'. I think maybe the 'xml' is wrong.

I have also attached the header of the ontology file as an image.

enter image description here

The reason I think there is a mistake with the code is the result I get which I showed in the image below: enter image description here

Thanks!

PS: Below is the full code in case there is something wrong with it:

import logging
import rdflib
import time

logging.basicConfig()
logger = logging.getLogger('logger')
logger.warning('The system may break down')

start_time = time.time()

g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)
query = """
select distinct ?p 
where { ?s ?p ?o}
        LIMIT 5
        """
result = g.query(query)
print(result.serialize(format='csv'))

print("--- %s seconds ---" % (time.time() - start_time))
1 Answers

There is nothing wrong with your code except that the format should be format='application/rdf+xml'.

Related