perplexity.ai
create n3 rdf for story peter rabbit with data on name of rabbits, what food they eat, where they are allowed to go, the names of those locations, and corresponding sparql queries wrapped in python rdflib
--> N3 in file peterrabbit.txt
# Names of all rabbits
import rdflib
print(rdflib.__version__)
g = rdflib.Graph()
g.parse("peterrabbit.txt", format="n3")
print(len(g))
q = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/vocab#>
SELECT ?name WHERE {
?rabbit ex:isRabbit true ;
foaf:name ?name .
}
"""
for row in g.query(q):
print(row.name)
5.0.0 73 Peter Mopsy Cottontail Mrs. Rabbit Flopsy
# What food does Peter eat?
q = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/vocab#>
SELECT ?foodName WHERE {
:Peter ex:eats ?food .
?food foaf:name ?foodName .
}
"""
for row in g.query(q, initNs={'': 'http://example.org/peterrabbit#'}):
print(row.foodName)
Radishes Chamomile Tea French Beans Parsley Lettuce
# Where is each rabbit allowed to go?
q = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/vocab#>
SELECT ?rabbitName ?locationName WHERE {
?rabbit ex:isRabbit true ;
foaf:name ?rabbitName ;
ex:allowedLocation ?loc .
?loc foaf:name ?locationName .
}
"""
for row in g.query(q):
print(f"{row.rabbitName}: {row.locationName}")
Peter: Lane Peter: Fields Mopsy: Fields Mopsy: Lane Cottontail: Lane Cottontail: Fields Mrs. Rabbit: Baker's Shop Mrs. Rabbit: Fields Mrs. Rabbit: Lane Flopsy: Fields Flopsy: Lane
# List all locations and which rabbits have visited them
q = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/vocab#>
SELECT ?rabbitName ?locationName WHERE {
?rabbit ex:isRabbit true ;
foaf:name ?rabbitName ;
ex:visited ?loc .
?loc foaf:name ?locationName .
}
"""
for row in g.query(q):
print(f"{row.rabbitName} visited {row.locationName}")
Peter visited Mr. McGregor's Garden Mopsy visited Lane Cottontail visited Lane Mrs. Rabbit visited Baker's Shop Flopsy visited Lane