File: slice.py

package info (click to toggle)
rdflib 7.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 77,852 kB
  • sloc: python: 59,555; sh: 153; makefile: 83; ruby: 74; xml: 45
file content (29 lines) | stat: -rw-r--r-- 844 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
RDFLib Graphs (and Resources) can be "sliced" with [] syntax

This is a short-hand for iterating over triples.

Combined with SPARQL paths (see `foafpaths.py`) - quite complex queries
can be realised.

See [`Graph.__getitem__`][rdflib.graph.Graph.__getitem__] for details
"""

from pathlib import Path

from rdflib import RDF, Graph
from rdflib.namespace import FOAF

EXAMPLES_DIR = Path(__file__).parent


if __name__ == "__main__":
    graph = Graph()
    graph.parse(f"{EXAMPLES_DIR / 'foaf.n3'}", format="n3")

    for person in graph[: RDF.type : FOAF.Person]:  # type: ignore[misc]
        friends = list(graph[person : FOAF.knows * "+" / FOAF.name])  # type: ignore[operator]
        if friends:
            print(f"{graph.value(person, FOAF.name)}'s circle of friends:")
            for name in friends:
                print(name)