I've loaded an RDF file in Python, using rdflib:
g = rdflib.Graph()
g.parse ( "foaf_ex.rdf" )
the *.rdf
defines a number of prefix/namespace pairs (e.g., foaf:
) and I know they come into g
because they're still there when I print g.serialize()
.
My question is, is there an easy way to go get "foaf:Person"
resolved from g
, i.e., turned into "http://xmlns.com/foaf/0.1/Person"
? getting an URIRef
straight from the initial prefixed URI would be even better, but it would help anyway if I might get at least the full URI string.
Answering myself to this old question, with the experience gathered meanwhile.
rdflib has a NamespaceManager
class, the Graph
object has a namespace_manager property, which can be passed to the a from_n3()
function, and the latter does what I need:
def from_n3(s, default=None, backend=None, nsm=None):
r'''
Creates the Identifier corresponding to the given n3 string.
>>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo')
True
>>> from_n3('"foo"@de') == Literal('foo', lang='de')
True
>>> from_n3('"""multi\nline\nstring"""@en') == Literal(
... 'multi\nline\nstring', lang='en')
True
>>> from_n3('42') == Literal(42)
True
>>> from_n3(Literal(42).n3()) == Literal(42)
True
>>> from_n3('"42"^^xsd:integer') == Literal(42)
True
>>> from rdflib import RDFS
>>> from_n3('rdfs:label') == RDFS['label']
True
>>> nsm = NamespaceManager(Graph())
>>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/')
>>> berlin = URIRef('http://dbpedia.org/resource/Berlin')
>>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin
True
'''
I've developed an extended version of NamespaceManager, the XNamespaceManager
, which makes it simple to access this and other functions.