0

I am trying to add triples to a Graph using python's rdflib package. The relations are provided as a list (a particular column in a dataframe)

sampleRelations = ['similarTo', 'brotherOf', 'capitalOf']
g = Graph()

# general relations
gen = Namespace('http://abcd.com/general#')
g.bind('gen',gen)

# Adding predefined relationships
g.add( (gen.relatedTo, RDFS.subClassOf, OWL.ObjectProperty) )

This works as usual. But, when iterating through a list:

for rel in sampleRelations:
    g.add( ('gen.'+rel, RDFS.subClassOf, OWL.ObjectProperty) )  

It throws an error : "Subject %s must be an rdflib term" % (s,).

relWithNamespace = gen+rel
print(relWithNamespace)
g.add( (relWithNamespace, RDFS.subClassOf, OWL.ObjectProperty) )

Error

AssertionError: Subject http://abcd.com/general#similarTo must be an rdflib term

I understand the problem. I'm looking for pointers which can circumvent this.

Betafish
  • 1,212
  • 3
  • 20
  • 45
  • 1
    You understand this? So why are you not creating an RDF term for the subject then? Did you read the docs: https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html ? – UninformedUser Nov 06 '19 at 09:35
  • By the way, the same issue like in your previous question: https://stackoverflow.com/questions/58519010/constructing-graph-using-rdflib-for-the-outputs-from-sparql-select-query-with - did you solve this? Did you read the same docs I linked to in my comments? The first code section in the link shows how to create RDF terms. And please provide the answer here to help others – UninformedUser Nov 06 '19 at 09:49
  • 1
    Thanks for the pointers, `rel = URIRef("http://abcd.com/general#"+rel)` then `gen.rel` then doing a `g.add((rel,RDFS.subClassOf, OWL.ObjectProperty ))` works. – Betafish Nov 06 '19 at 10:00
  • 1
    yeah,so now that you have the solution don't forget to provide it as an answer here and accept it. yes, you can indeed answer and accept your own solutions. might help others having the same question and questions with answer are ranked higher in search – UninformedUser Nov 06 '19 at 11:41

1 Answers1

2

RDF terms can be of BNode, URI Reference or a Literal

    sampleRelations = ['similarTo', 'brotherOf', 'capitalOf'`]
    g = Graph()

    # general relations
    gen = Namespace('http://abcd.com/general#')
    g.bind('gen',gen)

    # Adding predefined relationships
    g.add( (gen.relatedTo, RDFS.subClassOf, OWL.ObjectProperty) )
    for rel in sampleRelations :
        rel = URIRef('http://abcd.com/general#' + rel)        
        g.add((rel, RDFS.subClassOf, OWL.ObjectProperty))

URI Reference can be also done using:

for rel in sampleRelations :                
      g.add((gen.term(rel), RDFS.subClassOf, OWL.ObjectProperty))

or

for rel in sampleRelations :                
          g.add((gen[rel], RDFS.subClassOf, OWL.ObjectProperty))
Betafish
  • 1,212
  • 3
  • 20
  • 45