Parsing RDF into rdflib graphs

Reading an NT file

RDF data has various syntaxes ([ xml], [ n3], [ ntriples], trix, etc) that you might want to read. The simplest format is ntriples. Create the file demo.nt in the current directory with these two lines:

<> \
    <> .
<> \
    <> "Hello world" .

In an interactive python interpreter, try this:

>>> from rdflib.graph import Graph

>>> g = Graph()

>>> g.parse("demo.nt", format="nt") # DOCTEST ELLIPSIS
<Graph identifier=... (<class 'rdflib.Graph.Graph'>)>

>>> len(g)

>>> for stmt in g:
...     print stmt
 rdflib.Literal('Hello world', language=None, datatype=None))

The final lines show how RDFLib represents the two statements in the file. The statements themselves are just length-3 tuples; and the subjects, predicates, and objects are all rdflib types.

Reading remote graphs

Reading graphs from the net is just as straightforward:

>>> g.parse("")

>>> len(g)

The format defaults to xml, which is the common format for .rdf files you’ll find on the net.

See also the :meth:`~rdflib.graph.Graph.parse method <http://readthedocs/rdflib3/rdflib.Graph.Graph-class.html#parse>`_ and

other parsers supported by rdflib 3

Table Of Contents

Previous topic


Next topic

Using SPARQL to query an rdflib 3 graph