Search code examples
pythonrdfsemantic-webdbpediardflib

Adding RDF triple using property stored in a python Dictionary


I've been working with DBpedia for a GSoC project. I have to create triples using properties that are stored in another file.

For eg. my main file is main.py and the file with all the rules is rules.py.

Here's what I'm trying to/want to do:

rules.py

mapping_rules = {
    'family': 'relatedTo',
    'singer': 'MusicalArtist',
    'writer': 'Author'
}

main.py

import rules
import rdflib

dbo = rdflib.Namespace("http://dbpedia.org/ontology/")
dbr = rdflib.Namespace("http://dbpedia.org/resource/")

uri = "something"
res = "something"
p = mapping_rules[input()]
g.add((rdflib.URIRef(uri), dbo.p, rdflib.URIRef(res)))

I want the property of the triple to be decided dynamically.

If I use 'dbo.relatedTo'as value in mapping_rules.py, it shows error: Predicate dbo.related must be an rdflib term.

If I use dbo.relatedTo as value in mapping_rules.py, it throws name error: dbo is not defined.

If I use relatedTo in mapping_rules.py and use the above code, it adds a triple, but the property becomes dbo:p, whereas I wanted dbo:relatedTo.

I'm stuck here, Can anyone help? Thanks!!


Solution

  • OK, look at this example.

    Your code should be:

    import rules
    import rdflib
    
    dbo = rdflib.Namespace("http://dbpedia.org/ontology/")
    dbr = rdflib.Namespace("http://dbpedia.org/resource/")
    
    uri = "something"
    res = "something"
    p = mapping_rules[input()]
    g.add((rdflib.URIRef(uri), dbo[p], rdflib.URIRef(res)))
    

    Please note that dbo[p] is used instead of dbo.p. Your problem is not rdflib-specific, but rather related to working with Python objects.