4

I'm using rdflib to load an RDF graph into a Python scrpit I would like to print a list of subjects using the defined prefixes I doesn't find any method to apply the prefixes. My code

import rdflib
filepath = "... my file path ..."
gs = rdflib.Graph()
gs.bind('qs', "http://qs.org/")
gs.bind('foaf',"http://xmlns.com/foaf/0.1/")
gs.parse(filepath,format="nt")
mdstr = ""
for subject in gs.subjects():
    mdstr += str(subject) +"\n"
print(mdstr)

I get, for example http://qs.org/s12095 in place of qs:s12095

Moissinac
  • 63
  • 5
  • 1
    It seems that these bindings are used only in full graph serialization. Can't find any ready to use function, try `mdstr += ('_:' + subject if isinstance(subject, rdflib.BNode) else gs.namespace_manager.normalizeUri(subject)) + '\n'`. – Stanislav Kralin Sep 14 '18 at 19:37

1 Answers1

0

Relevant rdflib documentation. The prefixes in a graph are stored in its NamespaceManager object. To get rdflib to print the prefixes instead of the complete IRI, you can call its method .n3(graph.namespace_manager). So in your case, you can do:

from rdflib import Namespace
from rdflib.namespace import NamespaceManager

# bind namespace to the graph or its namespace manager
graph.bind('qs', Namespace('http://qs.org/'))

# assuming entity is IRI http://qs.org/s12095
print(entity) # --> http://qs.org/s12095
print(entity.n3(graph.namespace_manager)) # --> qs:s12095
coolharsh55
  • 1,179
  • 4
  • 12
  • 27