pythonrdfrdflib

How to determine or filter datatype of a rdflib literal?


I haven't used rdflib in a while and am writing some trivial code based on https://rdflib.readthedocs.io/en/stable/intro_to_graphs.html#basic-triple-matching

like

from rdflib import Graph

graph = Graph()
ttl_input = "dir/file.ttl"
graph.parse(ttl_input, format='ttl')

for s, p, o in graph.triples((None, None, None)):
    print(f"{s} {p} {o} {o}")

I would like to limit the returned graph.triples to ones where the object o has datatype xsd:anyURI


Solution

  • Like this:

    import rdflib
    from rdflib import Graph
    from rdflib.namespace import NamespaceManager, XSD
    
    graph = Graph()
    ttl_input = "dir/file.ttl"
    graph.parse(ttl_input, format='ttl')
    
    for s, p, o in graph:
        if o.__class__ == rdflib.term.Literal and o.datatype == XSD.anyURI:
            print(f"{s} {p} {o}")
    

    As for your previous question, replace the last line with this one:

            print(f"{s} {p} {graph.namespace_manager.expand_curie(o.value)}")