File: resource_example.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 (42 lines) | stat: -rw-r--r-- 1,383 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
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
RDFLib has a [`Resource`][rdflib.resource.Resource] class, for a resource-centric API.
The [`Graph`][rdflib.Graph] class also has a `resource` function that can be used
to create resources and manipulate them by quickly adding or querying for triples
where this resource is the subject.

This example shows `g.resource()` in action.
"""

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

if __name__ == "__main__":
    g = Graph()

    # Create a Resource within graph g
    bob = g.resource("http://example.com/bob")
    # .set replaces all other values
    bob.set(RDF.type, FOAF.Person)
    bob.set(FOAF.name, Literal("Bob"))

    bill = g.resource("http://example.com/bill")
    # .add adds to existing values
    bill.add(RDF.type, FOAF.Person)
    bill.add(RDF.type, FOAF.Agent)
    bill.set(RDFS.label, Literal("Bill"))

    bill.add(FOAF.knows, bob)

    # Resources returned when querying are 'auto-boxed' as resources:
    print(f"Bill knows: {bill.value(FOAF.knows).value(FOAF.name)}")

    # Slicing ([] syntax) can also be used:
    for friend in bill[FOAF.knows]:
        print(f"Bill knows: {next(friend[FOAF.name])}")

    # Or even quicker with paths:
    for friend in bill[FOAF.knows / FOAF.name]:
        print(f"Bill knows: {friend}")

    # Setting single properties is also possible:
    bill[RDFS.label] = Literal("William")