I am starting to use the rdflib
library for dealing with rdf data in Python. At the moment, I want to create a .n3
file of some rdf graph that looks like this:
@prefix ns1: <http://some.namespace/with/name#> .
@prefix ns2: <http://second.namespace/some/name#>
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<my_example> ns1:annotated_with [ ns1:annotation
ns2: annotation_value> ] ;
ns1:name "myname" .
That is, there is one example in this graph which is called my_example
, which has a name "myname". This example is annotated with an object whose annotation value is annotation value
. I wanted to construct this example in Python like so:
import rdflib
gg=rdflib.graph.Graph()
ns1 = rdflib.Namespace('http://some.namespace/with/name#')
ns2 = rdflib.Namespace('http://second.namespace/some/name#')
u = rdflib.term.URIRef('my_example')
gg.add((u, ns1.name, rdflib.Literal('myname')))
blank = rdflib.BNode()
gg.add((u, ns1.annotated_with, blank))
gg.add((blank, ns1.annotation, ns2.annotation_value))
print gg.serialize(format='n3')
Which should, in my oppinion, produce the correct result, and, in a way, it does. The result of the code above is a n3
string that looks like this:
@prefix ns1: <http://some.namespace/with/name#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<my_example> ns1:annotated_with [ ns1:annotation <http://second.namespace/some/name#annotation_value> ] ;
ns1:name "myname" .
Which is close, but I don't understand why rdflib
did not define, in the beginning of the file, the second namespace I am using. Is there a way to force it to do this?