How to add an Ontology IRI with the Python rdflib library?

513 views Asked by At

My problem is described here but the (maybe old) proposed solution does not work for me!

https://github.com/RDFLib/rdflib/issues/817

I would like to use rdflib to fill with Python the Ontology IRI like in the Ontology header of Protégé.

2

There are 2 answers

0
Edmond Chuc On

I am not sure what you mean by an ontology header. I'm assuming you want to programmatically modify the ontology metadata. The following code adds a few statements. You can use the add() and remove() methods on the graph object as shown below to alter your data.

from rdflib import OWL, RDF, RDFS, Graph, URIRef, Literal

g = Graph()

ontology_iri = URIRef("urn:example:ontology_iri")

g.add((ontology_iri, RDF.type, OWL.Ontology))
g.add((ontology_iri, RDFS.label, Literal("My ontology")))

g.print()

Output:

@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<urn:example:ontology_iri> a owl:Ontology ;
    rdfs:label "My ontology" .

0
Ludovic Bocken On

A new solution from here : https://github.com/RDFLib/rdflib/issues/817

from rdflib.extras.infixowl import Ontology

baseuri = rdflib.URIRef("http://purl.org/net/bel-epa/polti.owl")
nsuri = rdflib.URIRef(str(baseuri) + '#')
POLTI = rdflib.Namespace(nsuri)

g = rdflib.Graph(identifier=baseuri)
g.bind('polti', POLTI)

o = Ontology(
    identifier=nsuri,
    graph=g,
    comment=rdflib.Literal(
        "Georges Polti‘s Thirty-Six Dramatic Situations.", lang="en"
    ),
)
o.setVersion(rdflib.Literal("0.1.0", lang="en"))
print(g.serialize(format='pretty-xml'))

Output:

<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF
  xmlns:owl="http://www.w3.org/2002/07/owl#"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
  <owl:Ontology rdf:about="http://purl.org/net/bel-epa/polti.owl#">
    <rdfs:comment xml:lang="en">Georges Polti‘s Thirty-Six Dramatic Situations.</rdfs:comment>
    <owl:versionInfo xml:lang="en">0.1.0</owl:versionInfo>
  </owl:Ontology>
</rdf:RDF>