'How to add an Ontology IRI with the Python rdflib library?
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é.
Solution 1:[1]
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" .
Solution 2:[2]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Edmond Chuc |
| Solution 2 | Ludovic Bocken |
