<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://info216.wiki.uib.no/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Xin004</id>
	<title>info216 - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://info216.wiki.uib.no/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Xin004"/>
	<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/Special:Contributions/Xin004"/>
	<updated>2026-05-05T12:37:17Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.44.2</generator>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1870</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1870"/>
		<updated>2022-05-11T11:42:51Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
import spotlight&lt;br /&gt;
from spotlight import SpotlightException&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(address=SERVER,text=entity, confidence=CONFIDENCE)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_spotlight = annotate_entity(row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(&lt;br /&gt;
		ex + row[&#039;investigation&#039;] + &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	president_spotlight = annotate_entity(row[&#039;president&#039;])&lt;br /&gt;
&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), RDF.type, sem.Event)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasBeginTimeStamp, investigation_start)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasEndTimeStamp, investigation_end)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), tl.duration, investigation_days))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), dbp.president, URIRef(president_spotlight[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, dbp.president, dbr.president_underscore))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasSubEvent, investigation_result))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
	&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - XML==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# URL of xml data&lt;br /&gt;
url = &#039;http://feeds.bbci.co.uk/news/rss.xml&#039;&lt;br /&gt;
# Retrieve the xml data from the web-url.&lt;br /&gt;
resp = requests.get(url)&lt;br /&gt;
# Creating an ElementTree from the response content&lt;br /&gt;
tree = ET.ElementTree(ET.fromstring(resp.content))&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
# I just realized this is cheating, but whatever, you should do it with xmltree&lt;br /&gt;
writerDict = {&lt;br /&gt;
    &amp;quot;Mon&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Tue&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Wed&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Thu&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Fri&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Sat&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;,&lt;br /&gt;
    &amp;quot;Sun&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
for item in root.findall(&amp;quot;./channel/item&amp;quot;):&lt;br /&gt;
    copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
    News_article_id = URIRef(item.find(&amp;quot;guid&amp;quot;).text)&lt;br /&gt;
    title = Literal(item.find(&amp;quot;title&amp;quot;).text)&lt;br /&gt;
    description = Literal(item.find(&amp;quot;description&amp;quot;).text)&lt;br /&gt;
    link = URIRef(item.find(&amp;quot;link&amp;quot;).text)&lt;br /&gt;
    pubDate = Literal(item.find(&amp;quot;pubDate&amp;quot;).text)&lt;br /&gt;
    writerName = ex[writerDict[pubDate[:3]]]&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.title, title))&lt;br /&gt;
    g.add((News_article_id, ex.description, description))&lt;br /&gt;
    g.add((News_article_id, ex.source_link, link))&lt;br /&gt;
    g.add((News_article_id, ex.pubDate, pubDate))&lt;br /&gt;
    g.add((News_article_id, ex.copyright, copyright))&lt;br /&gt;
    g.add((News_article_id, RDF.type, ex.News_article))&lt;br /&gt;
    g.add((News_article_id, RDF.type, prov.Entity))&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.authoredBy, writerName))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Person))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Agent))&lt;br /&gt;
    g.add((ex.authoredBy, RDF.type, prov.Generation))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 2==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.minCardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.someValuesFrom, ex.University))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Graduate, br]) &lt;br /&gt;
                #[ex.Person, br] also someValueFrom implies a cardinality of at least one so they would be equivalent.&lt;br /&gt;
                #[ex.Person, ex.Graduate, br] would be redundant since intersection is associative. &lt;br /&gt;
g.add((ex.University_graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;), Literal(&amp;quot;F&amp;quot;)])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.grade, RDFS.range, b1))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Student, b1, b2])&lt;br /&gt;
g.add((ex.Straight_A_student, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;)])&lt;br /&gt;
b4 = BNode()&lt;br /&gt;
g.add((b4, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b4, OWL.oneOf, b3))&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b4))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Person, b1, b5]) &lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.average_grade))&lt;br /&gt;
g.add((b1, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.student_number))&lt;br /&gt;
g.add((b2, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
Collection(g, b3, [ex.Person, b1, b2]) &lt;br /&gt;
g.add((ex.Student, OWL.intersectionOf, b3))&lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Bachelor_course, ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
#g.add((b1, RDF.type, OWL.Class))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Course, RDF.type, b1))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
g.add((ex.Bachelor_student, RDFS.subClassOf, ex.Student))&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Student, b1])&lt;br /&gt;
g.add((ex.Bachelor_student, OWL.intersectionOf, b2))&lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(1)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex.Bachelor_course])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex.Master_student, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lab 11: Semantic Lifting - HTML==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs&lt;br /&gt;
from rdflib import Graph, Literal, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF, SKOS, XSD&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Download html from URL and parse it with BeautifulSoup.&lt;br /&gt;
url = &amp;quot;https://www.semanticscholar.org/topic/Knowledge-Graph/159858&amp;quot;&lt;br /&gt;
page = requests.get(url)&lt;br /&gt;
html = bs(page.content, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
# print(html.prettify())&lt;br /&gt;
&lt;br /&gt;
# Find the html that surrounds all the papers&lt;br /&gt;
papers = html.find_all(&#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-container&#039;})&lt;br /&gt;
# Find the html that surrounds the info box&lt;br /&gt;
topic = html.find_all(&lt;br /&gt;
    &#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-item__left-column entity-header&#039;})&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Iterate through each paper to make triples:&lt;br /&gt;
for paper in papers:&lt;br /&gt;
    # e.g selecting title.&lt;br /&gt;
    title = paper.find(&#039;div&#039;, attrs={&#039;class&#039;: &#039;timeline-paper-title&#039;}).text&lt;br /&gt;
    author = paper.find(&#039;span&#039;, attrs={&#039;class&#039;: &#039;author-list&#039;}).text&lt;br /&gt;
    papper_year = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;paper-year&amp;quot;}).text&lt;br /&gt;
    corpus_ID = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;corpus-id&amp;quot;}).text&lt;br /&gt;
    corpus_ID = corpus_ID.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
    c_id = corpus_ID.replace(&amp;quot;Corpus_ID:_&amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
    article = URIRef(ex + c_id)&lt;br /&gt;
&lt;br /&gt;
    # Adding tripels&lt;br /&gt;
    g.add((article, RDF.type, ex.paper))&lt;br /&gt;
    g.add((article, ex.HasID, Literal(c_id, datatype=XSD.int)))&lt;br /&gt;
    g.add((article, ex.HasTitle, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((article, ex.Publisher_year, Literal(papper_year, datatype=XSD.year)))&lt;br /&gt;
&lt;br /&gt;
    author = author.split(&amp;quot;, &amp;quot;)&lt;br /&gt;
    for x in author:&lt;br /&gt;
        name = x.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
        name = URIRef(ex + name)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, ex.hasAuthor, name))&lt;br /&gt;
&lt;br /&gt;
# Iterate through the info box to make triples:&lt;br /&gt;
    for items in topic:&lt;br /&gt;
        main_topic = items.find(&#039;h1&#039;, attrs={&#039;class&#039;: &#039;entity-name&#039;}).text&lt;br /&gt;
        related_topic = items.find(&lt;br /&gt;
            &#039;div&#039;, attrs={&#039;class&#039;: &#039;entity-aliases&#039;}).text&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot;Known as: &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(f&#039;\xa0Expand&#039;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot; &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        main_topic = main_topic.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        main_topic = URIRef(ex + main_topic)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, RDF.type, SKOS.Concept))&lt;br /&gt;
        g.add((article, SKOS.hasTopConcept, main_topic))&lt;br /&gt;
&lt;br /&gt;
    related_topic = related_topic.split(&#039;,&#039;)&lt;br /&gt;
&lt;br /&gt;
    for related_labels in related_topic:&lt;br /&gt;
        related_topic = URIRef(ex + related_labels)&lt;br /&gt;
        g.add((article, SKOS.broader, related_topic))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Owlready2==&lt;br /&gt;
Martin&#039;s solution. NOTE: intead of using &amp;quot;is_a&amp;quot; to define classes like I have mostly done, use &amp;quot;equivalent_to&amp;quot; to make the resoner more powerful (and work at all in this case).  &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import *&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class UniversityDegree(Degree): pass&lt;br /&gt;
    class UniversityGraduate(Graduate): &lt;br /&gt;
        is_a = [hasDegree.some(UniversityDegree)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class A(Grade): pass&lt;br /&gt;
    class B(Grade): pass&lt;br /&gt;
    class C(Grade): pass&lt;br /&gt;
    class D(Grade): pass&lt;br /&gt;
    class E(Grade): pass&lt;br /&gt;
    class F(Grade): pass&lt;br /&gt;
&lt;br /&gt;
Grade.is_a.append(OneOf([A, B, C, D, E, F]))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        is_a = [hasGrade.only(A)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
#Graduate.is_a.append(hasGrade.only(OneOf[A,B,C,D,E]))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
with onto:&lt;br /&gt;
    class StudentNumber(Thing):pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; StudentNumber, FunctionalProperty, InverseFunctionalProperty):pass&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
with onto:&lt;br /&gt;
    class AverageGrade(Grade):pass&lt;br /&gt;
    class hasAverageGrade(Student &amp;gt;&amp;gt; AverageGrade):pass&lt;br /&gt;
Student.is_a.append(hasAverageGrade.exactly(1,AverageGrade))&lt;br /&gt;
Student.is_a.append(hasStudentNumber.exactly(1,StudentNumber))&lt;br /&gt;
    &lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing):pass&lt;br /&gt;
    class BachelorCourse(Course):pass&lt;br /&gt;
    class MasterCourse(Course):pass&lt;br /&gt;
    class PhDCourse(Course):pass&lt;br /&gt;
    &lt;br /&gt;
Course.is_a.append(OneOf([BachelorCourse, MasterCourse, PhDCourse]))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class takesCourse(Student&amp;gt;&amp;gt;Course):pass&lt;br /&gt;
    class BachelorStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(Course)&lt;br /&gt;
        ]&lt;br /&gt;
        &lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class MasterOrBachelorCourse(Course):pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(PhDCourse)) &amp;amp;&lt;br /&gt;
            takesCourse.max(1,BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(MasterCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(BachelorCourse))&amp;amp;&lt;br /&gt;
            takesCourse.max(2,MasterCourse)&amp;amp;&lt;br /&gt;
            takesCourse.some(PhDCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
# In comparison to lab 10..&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&lt;br /&gt;
#print(onto2graph(onto).serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;graduate is: &amp;quot;, Graduate.is_a)&lt;br /&gt;
print(&amp;quot;cade is: &amp;quot;, cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative solution. More pro from Andreas, but it&#039;s a not so thoroughly tested draft for us teacher assistents he stresses (it&#039;s new material for us), so you might need to make some changes (like the one recommended above: equivalent_to instead of is_a).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import get_ontology, Thing, ObjectProperty&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
from owlready2 import destroy_entity&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
# anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasDegree(ObjectProperty): pass&lt;br /&gt;
    class degreeFrom(ObjectProperty): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class University(Thing): pass&lt;br /&gt;
    class UniversityGraduate(Thing): &lt;br /&gt;
        hasDegree: Degree&lt;br /&gt;
        is_a = [hasDegree.some(Degree &amp;amp; degreeFrom.some(University))]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import declare_datatype&lt;br /&gt;
class XSDString(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def str_parser(s): return s&lt;br /&gt;
def str_unparser(s): return s&lt;br /&gt;
declare_datatype(XSDString, &#039;http://www.w3.org/2001/XMLSchema#string&#039;, str_parser, str_unparser)&lt;br /&gt;
&lt;br /&gt;
# a grade is either an A, B, C, D, E or F&lt;br /&gt;
from owlready2 import OneOf&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    grade_C = Grade()&lt;br /&gt;
    grade_C.charGrade = [&#039;C&#039;]&lt;br /&gt;
    grade_D = Grade()&lt;br /&gt;
    grade_D.charGrade = [&#039;D&#039;]&lt;br /&gt;
    grade_E = Grade()&lt;br /&gt;
    grade_E.charGrade = [&#039;E&#039;]&lt;br /&gt;
    grade_F = Grade()&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B, grade_C, grade_D, grade_E, grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate has no F grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A,  # ...&lt;br /&gt;
        grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeF(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_F])]&lt;br /&gt;
    class Graduate(Student):&lt;br /&gt;
        equivalent_to = [Student &amp;amp; ~ hasGrade.some(GradeF)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a student has a single unique student number&lt;br /&gt;
class XSDInt(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return int(s)&lt;br /&gt;
def int_unparser(i): return str(i)&lt;br /&gt;
declare_datatype(XSDInt, &#039;http://www.w3.org/2001/XMLSchema#int&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import FunctionalProperty, InverseFunctionalProperty&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; XSDInt): &lt;br /&gt;
        is_a = [FunctionalProperty, InverseFunctionalProperty]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# each student has exactly one average grade&lt;br /&gt;
class XSDFloat(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return float(s)&lt;br /&gt;
def int_unparser(f): return str(f)&lt;br /&gt;
declare_datatype(XSDFloat, &#039;http://www.w3.org/2001/XMLSchema#float&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasAverageGrade(Grade &amp;gt;&amp;gt; XSDFloat): pass&lt;br /&gt;
    Student.is_a.append(hasAverageGrade.exactly(1, XSDFloat))&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a bachelor student takes only bachelor courses&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a masters student takes only master courses, except for at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(MasterCourse | BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(1, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D student takes only Ph.D courses, except for at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(PhDCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(PhDCourse | MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(2, MasterCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D. student cannot take a bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.max(0, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# ...alternative solution&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [Student &amp;amp; ~ takesCourse.some(BachelorCourse)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [Student &amp;amp; hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
# if you have more time: &lt;br /&gt;
# populate the ontology with individuals&lt;br /&gt;
# a straight A student is a student that has only A grades&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            Student &amp;amp;&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
    # add individual&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    cade.hasGrade.append(grade_A)&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import close_world&lt;br /&gt;
close_world(onto)  # because of the &amp;quot;only&amp;quot;-restriction&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Knowledge graph embeddings==&lt;br /&gt;
https://colab.research.google.com/drive/1sHusTjvmHtV6PkzIatLTMPzHuseAF6N1?usp=sharing&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1869</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1869"/>
		<updated>2022-05-11T11:26:44Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
import spotlight&lt;br /&gt;
from spotlight import SpotlightException&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(address=SERVER,text=entity, confidence=CONFIDENCE)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_spotlight = annotate_entity(row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(&lt;br /&gt;
		ex + row[&#039;investigation&#039;] + &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	president_spotlight = annotate_entity(row[&#039;president&#039;])&lt;br /&gt;
&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), RDF.type, sem.Event)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasBeginTimeStamp, investigation_start)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasEndTimeStamp, investigation_end)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), tl.duration, investigation_days))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), dbp.president, URIRef(president_spotlight[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, dbp.president, dbr.president_underscore))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasSubEvent, investigation_result))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
	&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - XML==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# URL of xml data&lt;br /&gt;
url = &#039;http://feeds.bbci.co.uk/news/rss.xml&#039;&lt;br /&gt;
# Retrieve the xml data from the web-url.&lt;br /&gt;
resp = requests.get(url)&lt;br /&gt;
# Creating an ElementTree from the response content&lt;br /&gt;
tree = ET.ElementTree(ET.fromstring(resp.content))&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
# I just realized this is cheating, but whatever, you should do it with xmltree&lt;br /&gt;
writerDict = {&lt;br /&gt;
    &amp;quot;Mon&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Tue&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Wed&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Thu&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Fri&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Sat&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;,&lt;br /&gt;
    &amp;quot;Sun&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
for item in root.findall(&amp;quot;./channel/item&amp;quot;):&lt;br /&gt;
    copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
    News_article_id = URIRef(item.find(&amp;quot;guid&amp;quot;).text)&lt;br /&gt;
    title = Literal(item.find(&amp;quot;title&amp;quot;).text)&lt;br /&gt;
    description = Literal(item.find(&amp;quot;description&amp;quot;).text)&lt;br /&gt;
    link = URIRef(item.find(&amp;quot;link&amp;quot;).text)&lt;br /&gt;
    pubDate = Literal(item.find(&amp;quot;pubDate&amp;quot;).text)&lt;br /&gt;
    writerName = ex[writerDict[pubDate[:3]]]&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.title, title))&lt;br /&gt;
    g.add((News_article_id, ex.description, description))&lt;br /&gt;
    g.add((News_article_id, ex.source_link, link))&lt;br /&gt;
    g.add((News_article_id, ex.pubDate, pubDate))&lt;br /&gt;
    g.add((News_article_id, ex.copyright, copyright))&lt;br /&gt;
    g.add((News_article_id, RDF.type, ex.News_article))&lt;br /&gt;
    g.add((News_article_id, RDF.type, prov.Entity))&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.authoredBy, writerName))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Person))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Agent))&lt;br /&gt;
    g.add((ex.authoredBy, RDF.type, prov.Generation))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 2==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.minCardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.someValuesFrom, ex.University))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Graduate, br]) &lt;br /&gt;
                #[ex.Person, br] also someValueFrom implies a cardinality of at least one so they would be equivalent.&lt;br /&gt;
                #[ex.Person, ex.Graduate, br] would be redundant since intersection is associative. &lt;br /&gt;
g.add((ex.University_graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;), Literal(&amp;quot;F&amp;quot;)])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.grade, RDFS.range, b1))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Student, b1, b2])&lt;br /&gt;
g.add((ex.Straight_A_student, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;)])&lt;br /&gt;
b4 = BNode()&lt;br /&gt;
g.add((b4, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b4, OWL.oneOf, b3))&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b4))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Person, b1, b5]) &lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.average_grade))&lt;br /&gt;
g.add((b1, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.student_number))&lt;br /&gt;
g.add((b2, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
Collection(g, b3, [ex.Person, b1, b2]) &lt;br /&gt;
g.add((ex.Student, OWL.intersectionOf, b3))&lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Bachelor_course, ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
#g.add((b1, RDF.type, OWL.Class))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Course, RDF.type, b1))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
g.add((ex.Bachelor_student, RDFS.subClassOf, ex.Student))&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Student, b1])&lt;br /&gt;
g.add((ex.Bachelor_student, OWL.intersectionOf, b2))&lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(1)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex.Bachelor_course])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex.Master_student, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lab 11: Semantic Lifting - HTML==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs&lt;br /&gt;
from rdflib import Graph, Literal, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF, SKOS, XSD&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Download html from URL and parse it with BeautifulSoup.&lt;br /&gt;
url = &amp;quot;https://www.semanticscholar.org/topic/Knowledge-Graph/159858&amp;quot;&lt;br /&gt;
page = requests.get(url)&lt;br /&gt;
html = bs(page.content, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
# print(html.prettify())&lt;br /&gt;
&lt;br /&gt;
# Find the html that surrounds all the papers&lt;br /&gt;
papers = html.find_all(&#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-container&#039;})&lt;br /&gt;
# Find the html that surrounds the info box&lt;br /&gt;
topic = html.find_all(&lt;br /&gt;
    &#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-item__left-column entity-header&#039;})&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Iterate through each paper to make triples:&lt;br /&gt;
for paper in papers:&lt;br /&gt;
    # e.g selecting title.&lt;br /&gt;
    title = paper.find(&#039;div&#039;, attrs={&#039;class&#039;: &#039;timeline-paper-title&#039;}).text&lt;br /&gt;
    author = paper.find(&#039;span&#039;, attrs={&#039;class&#039;: &#039;author-list&#039;}).text&lt;br /&gt;
    papper_year = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;paper-year&amp;quot;}).text&lt;br /&gt;
    corpus_ID = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;corpus-id&amp;quot;}).text&lt;br /&gt;
    corpus_ID = corpus_ID.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
    c_id = corpus_ID.replace(&amp;quot;Corpus_ID:_&amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
    article = URIRef(ex + c_id)&lt;br /&gt;
&lt;br /&gt;
    # Adding tripels&lt;br /&gt;
    g.add((article, RDF.type, ex.paper))&lt;br /&gt;
    g.add((article, ex.HasID, Literal(c_id, datatype=XSD.int)))&lt;br /&gt;
    g.add((article, ex.HasTitle, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((article, ex.Publisher_year, Literal(papper_year, datatype=XSD.year)))&lt;br /&gt;
&lt;br /&gt;
    author = author.split(&amp;quot;, &amp;quot;)&lt;br /&gt;
    for x in author:&lt;br /&gt;
        name = x.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
        name = URIRef(ex + name)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, ex.hasAuthor, name))&lt;br /&gt;
&lt;br /&gt;
# Iterate through the info box to make triples:&lt;br /&gt;
    for items in topic:&lt;br /&gt;
        main_topic = items.find(&#039;h1&#039;, attrs={&#039;class&#039;: &#039;entity-name&#039;}).text&lt;br /&gt;
        related_topic = items.find(&lt;br /&gt;
            &#039;div&#039;, attrs={&#039;class&#039;: &#039;entity-aliases&#039;}).text&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot;Known as: &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(f&#039;\xa0Expand&#039;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot; &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        main_topic = main_topic.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        main_topic = URIRef(ex + main_topic)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, RDF.type, SKOS.Concept))&lt;br /&gt;
        g.add((article, SKOS.hasTopConcept, main_topic))&lt;br /&gt;
&lt;br /&gt;
    related_topic = related_topic.split(&#039;,&#039;)&lt;br /&gt;
&lt;br /&gt;
    for related_labels in related_topic:&lt;br /&gt;
        related_topic = URIRef(ex + related_labels)&lt;br /&gt;
        g.add((article, SKOS.broader, related_topic))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Owlready2==&lt;br /&gt;
Martin&#039;s solution. NOTE: intead of using &amp;quot;is_a&amp;quot; to define classes like I have mostly done, use &amp;quot;equivalent_to&amp;quot; to make the resoner more powerful (and work at all in this case).  &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import *&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class UniversityDegree(Degree): pass&lt;br /&gt;
    class UniversityGraduate(Graduate): &lt;br /&gt;
        is_a = [hasDegree.some(UniversityDegree)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class A(Grade): pass&lt;br /&gt;
    class B(Grade): pass&lt;br /&gt;
    class C(Grade): pass&lt;br /&gt;
    class D(Grade): pass&lt;br /&gt;
    class E(Grade): pass&lt;br /&gt;
    class F(Grade): pass&lt;br /&gt;
&lt;br /&gt;
Grade.is_a.append(OneOf([A, B, C, D, E, F]))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        is_a = [hasGrade.only(A)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
#Graduate.is_a.append(hasGrade.only(OneOf[A,B,C,D,E]))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
with onto:&lt;br /&gt;
    class StudentNumber(Thing):pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; StudentNumber, FunctionalProperty, InverseFunctionalProperty):pass&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
with onto:&lt;br /&gt;
    class AverageGrade(Grade):pass&lt;br /&gt;
    class hasAverageGrade(Student &amp;gt;&amp;gt; AverageGrade):pass&lt;br /&gt;
Student.is_a.append(hasAverageGrade.exactly(1,AverageGrade))&lt;br /&gt;
Student.is_a.append(hasStudentNumber.exactly(1,StudentNumber))&lt;br /&gt;
    &lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing):pass&lt;br /&gt;
    class BachelorCourse(Course):pass&lt;br /&gt;
    class MasterCourse(Course):pass&lt;br /&gt;
    class PhDCourse(Course):pass&lt;br /&gt;
    &lt;br /&gt;
Course.is_a.append(OneOf([BachelorCourse, MasterCourse, PhDCourse]))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class takesCourse(Student&amp;gt;&amp;gt;Course):pass&lt;br /&gt;
    class BachelorStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(Course)&lt;br /&gt;
        ]&lt;br /&gt;
        &lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class MasterOrBachelorCourse(Course):pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(PhDCourse)) &amp;amp;&lt;br /&gt;
            takesCourse.max(1,BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(MasterCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(BachelorCourse))&amp;amp;&lt;br /&gt;
            takesCourse.max(2,MasterCourse)&amp;amp;&lt;br /&gt;
            takesCourse.some(PhDCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
# In comparison to lab 10..&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&lt;br /&gt;
#print(onto2graph(onto).serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;graduate is: &amp;quot;, Graduate.is_a)&lt;br /&gt;
print(&amp;quot;cade is: &amp;quot;, cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative solution. More pro from Andreas, but only a quick draft he stresses (but I still think it&#039;s valuable to share), so you might need to make some changes (like the one recommended above: equivalent_to instead of is_a).&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import get_ontology, Thing, ObjectProperty&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
from owlready2 import destroy_entity&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
# anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasDegree(ObjectProperty): pass&lt;br /&gt;
    class degreeFrom(ObjectProperty): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class University(Thing): pass&lt;br /&gt;
    class UniversityGraduate(Thing): &lt;br /&gt;
        hasDegree: Degree&lt;br /&gt;
        is_a = [hasDegree.some(Degree &amp;amp; degreeFrom.some(University))]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import declare_datatype&lt;br /&gt;
class XSDString(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def str_parser(s): return s&lt;br /&gt;
def str_unparser(s): return s&lt;br /&gt;
declare_datatype(XSDString, &#039;http://www.w3.org/2001/XMLSchema#string&#039;, str_parser, str_unparser)&lt;br /&gt;
&lt;br /&gt;
# a grade is either an A, B, C, D, E or F&lt;br /&gt;
from owlready2 import OneOf&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    grade_C = Grade()&lt;br /&gt;
    grade_C.charGrade = [&#039;C&#039;]&lt;br /&gt;
    grade_D = Grade()&lt;br /&gt;
    grade_D.charGrade = [&#039;D&#039;]&lt;br /&gt;
    grade_E = Grade()&lt;br /&gt;
    grade_E.charGrade = [&#039;E&#039;]&lt;br /&gt;
    grade_F = Grade()&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B, grade_C, grade_D, grade_E, grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate has no F grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A,  # ...&lt;br /&gt;
        grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeF(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_F])]&lt;br /&gt;
    class Graduate(Student):&lt;br /&gt;
        equivalent_to = [Student &amp;amp; ~ hasGrade.some(GradeF)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a student has a single unique student number&lt;br /&gt;
class XSDInt(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return int(s)&lt;br /&gt;
def int_unparser(i): return str(i)&lt;br /&gt;
declare_datatype(XSDInt, &#039;http://www.w3.org/2001/XMLSchema#int&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import FunctionalProperty, InverseFunctionalProperty&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; XSDInt): &lt;br /&gt;
        is_a = [FunctionalProperty, InverseFunctionalProperty]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# each student has exactly one average grade&lt;br /&gt;
class XSDFloat(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return float(s)&lt;br /&gt;
def int_unparser(f): return str(f)&lt;br /&gt;
declare_datatype(XSDFloat, &#039;http://www.w3.org/2001/XMLSchema#float&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasAverageGrade(Grade &amp;gt;&amp;gt; XSDFloat): pass&lt;br /&gt;
    Student.is_a.append(hasAverageGrade.exactly(1, XSDFloat))&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a bachelor student takes only bachelor courses&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a masters student takes only master courses, except for at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(MasterCourse | BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(1, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D student takes only Ph.D courses, except for at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(PhDCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(PhDCourse | MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(2, MasterCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D. student cannot take a bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.max(0, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# ...alternative solution&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [Student &amp;amp; ~ takesCourse.some(BachelorCourse)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [Student &amp;amp; hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
# if you have more time: &lt;br /&gt;
# populate the ontology with individuals&lt;br /&gt;
# a straight A student is a student that has only A grades&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            Student &amp;amp;&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
    # add individual&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    cade.hasGrade.append(grade_A)&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import close_world&lt;br /&gt;
close_world(onto)  # because of the &amp;quot;only&amp;quot;-restriction&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1868</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1868"/>
		<updated>2022-05-11T11:24:44Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
import spotlight&lt;br /&gt;
from spotlight import SpotlightException&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(address=SERVER,text=entity, confidence=CONFIDENCE)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_spotlight = annotate_entity(row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(&lt;br /&gt;
		ex + row[&#039;investigation&#039;] + &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	president_spotlight = annotate_entity(row[&#039;president&#039;])&lt;br /&gt;
&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), RDF.type, sem.Event)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasBeginTimeStamp, investigation_start)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasEndTimeStamp, investigation_end)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), tl.duration, investigation_days))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), dbp.president, URIRef(president_spotlight[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, dbp.president, dbr.president_underscore))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasSubEvent, investigation_result))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
	&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - XML==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# URL of xml data&lt;br /&gt;
url = &#039;http://feeds.bbci.co.uk/news/rss.xml&#039;&lt;br /&gt;
# Retrieve the xml data from the web-url.&lt;br /&gt;
resp = requests.get(url)&lt;br /&gt;
# Creating an ElementTree from the response content&lt;br /&gt;
tree = ET.ElementTree(ET.fromstring(resp.content))&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
# I just realized this is cheating, but whatever, you should do it with xmltree&lt;br /&gt;
writerDict = {&lt;br /&gt;
    &amp;quot;Mon&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Tue&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Wed&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Thu&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Fri&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Sat&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;,&lt;br /&gt;
    &amp;quot;Sun&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
for item in root.findall(&amp;quot;./channel/item&amp;quot;):&lt;br /&gt;
    copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
    News_article_id = URIRef(item.find(&amp;quot;guid&amp;quot;).text)&lt;br /&gt;
    title = Literal(item.find(&amp;quot;title&amp;quot;).text)&lt;br /&gt;
    description = Literal(item.find(&amp;quot;description&amp;quot;).text)&lt;br /&gt;
    link = URIRef(item.find(&amp;quot;link&amp;quot;).text)&lt;br /&gt;
    pubDate = Literal(item.find(&amp;quot;pubDate&amp;quot;).text)&lt;br /&gt;
    writerName = ex[writerDict[pubDate[:3]]]&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.title, title))&lt;br /&gt;
    g.add((News_article_id, ex.description, description))&lt;br /&gt;
    g.add((News_article_id, ex.source_link, link))&lt;br /&gt;
    g.add((News_article_id, ex.pubDate, pubDate))&lt;br /&gt;
    g.add((News_article_id, ex.copyright, copyright))&lt;br /&gt;
    g.add((News_article_id, RDF.type, ex.News_article))&lt;br /&gt;
    g.add((News_article_id, RDF.type, prov.Entity))&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.authoredBy, writerName))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Person))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Agent))&lt;br /&gt;
    g.add((ex.authoredBy, RDF.type, prov.Generation))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 2==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.minCardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.someValuesFrom, ex.University))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Graduate, br]) &lt;br /&gt;
                #[ex.Person, br] also someValueFrom implies a cardinality of at least one so they would be equivalent.&lt;br /&gt;
                #[ex.Person, ex.Graduate, br] would be redundant since intersection is associative. &lt;br /&gt;
g.add((ex.University_graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;), Literal(&amp;quot;F&amp;quot;)])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.grade, RDFS.range, b1))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Student, b1, b2])&lt;br /&gt;
g.add((ex.Straight_A_student, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;)])&lt;br /&gt;
b4 = BNode()&lt;br /&gt;
g.add((b4, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b4, OWL.oneOf, b3))&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b4))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Person, b1, b5]) &lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.average_grade))&lt;br /&gt;
g.add((b1, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.student_number))&lt;br /&gt;
g.add((b2, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
Collection(g, b3, [ex.Person, b1, b2]) &lt;br /&gt;
g.add((ex.Student, OWL.intersectionOf, b3))&lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Bachelor_course, ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
#g.add((b1, RDF.type, OWL.Class))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Course, RDF.type, b1))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
g.add((ex.Bachelor_student, RDFS.subClassOf, ex.Student))&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Student, b1])&lt;br /&gt;
g.add((ex.Bachelor_student, OWL.intersectionOf, b2))&lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(1)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex.Bachelor_course])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex.Master_student, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lab 11: Semantic Lifting - HTML==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs&lt;br /&gt;
from rdflib import Graph, Literal, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF, SKOS, XSD&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Download html from URL and parse it with BeautifulSoup.&lt;br /&gt;
url = &amp;quot;https://www.semanticscholar.org/topic/Knowledge-Graph/159858&amp;quot;&lt;br /&gt;
page = requests.get(url)&lt;br /&gt;
html = bs(page.content, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
# print(html.prettify())&lt;br /&gt;
&lt;br /&gt;
# Find the html that surrounds all the papers&lt;br /&gt;
papers = html.find_all(&#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-container&#039;})&lt;br /&gt;
# Find the html that surrounds the info box&lt;br /&gt;
topic = html.find_all(&lt;br /&gt;
    &#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-item__left-column entity-header&#039;})&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Iterate through each paper to make triples:&lt;br /&gt;
for paper in papers:&lt;br /&gt;
    # e.g selecting title.&lt;br /&gt;
    title = paper.find(&#039;div&#039;, attrs={&#039;class&#039;: &#039;timeline-paper-title&#039;}).text&lt;br /&gt;
    author = paper.find(&#039;span&#039;, attrs={&#039;class&#039;: &#039;author-list&#039;}).text&lt;br /&gt;
    papper_year = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;paper-year&amp;quot;}).text&lt;br /&gt;
    corpus_ID = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;corpus-id&amp;quot;}).text&lt;br /&gt;
    corpus_ID = corpus_ID.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
    c_id = corpus_ID.replace(&amp;quot;Corpus_ID:_&amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
    article = URIRef(ex + c_id)&lt;br /&gt;
&lt;br /&gt;
    # Adding tripels&lt;br /&gt;
    g.add((article, RDF.type, ex.paper))&lt;br /&gt;
    g.add((article, ex.HasID, Literal(c_id, datatype=XSD.int)))&lt;br /&gt;
    g.add((article, ex.HasTitle, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((article, ex.Publisher_year, Literal(papper_year, datatype=XSD.year)))&lt;br /&gt;
&lt;br /&gt;
    author = author.split(&amp;quot;, &amp;quot;)&lt;br /&gt;
    for x in author:&lt;br /&gt;
        name = x.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
        name = URIRef(ex + name)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, ex.hasAuthor, name))&lt;br /&gt;
&lt;br /&gt;
# Iterate through the info box to make triples:&lt;br /&gt;
    for items in topic:&lt;br /&gt;
        main_topic = items.find(&#039;h1&#039;, attrs={&#039;class&#039;: &#039;entity-name&#039;}).text&lt;br /&gt;
        related_topic = items.find(&lt;br /&gt;
            &#039;div&#039;, attrs={&#039;class&#039;: &#039;entity-aliases&#039;}).text&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot;Known as: &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(f&#039;\xa0Expand&#039;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot; &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        main_topic = main_topic.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        main_topic = URIRef(ex + main_topic)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, RDF.type, SKOS.Concept))&lt;br /&gt;
        g.add((article, SKOS.hasTopConcept, main_topic))&lt;br /&gt;
&lt;br /&gt;
    related_topic = related_topic.split(&#039;,&#039;)&lt;br /&gt;
&lt;br /&gt;
    for related_labels in related_topic:&lt;br /&gt;
        related_topic = URIRef(ex + related_labels)&lt;br /&gt;
        g.add((article, SKOS.broader, related_topic))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Owlready2==&lt;br /&gt;
Martin&#039;s solution. NOTE: intead of using &amp;quot;is_a&amp;quot; to define classes like I have done, use &amp;quot;equivalent_to&amp;quot; to make the resoner work.  &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import *&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp_owlready2.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class UniversityDegree(Degree): pass&lt;br /&gt;
    class UniversityGraduate(Graduate): &lt;br /&gt;
        is_a = [hasDegree.some(UniversityDegree)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class A(Grade): pass&lt;br /&gt;
    class B(Grade): pass&lt;br /&gt;
    class C(Grade): pass&lt;br /&gt;
    class D(Grade): pass&lt;br /&gt;
    class E(Grade): pass&lt;br /&gt;
    class F(Grade): pass&lt;br /&gt;
&lt;br /&gt;
Grade.is_a.append(OneOf([A, B, C, D, E, F]))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        is_a = [hasGrade.only(A)]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
#Graduate.is_a.append(hasGrade.only(OneOf[A,B,C,D,E]))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
with onto:&lt;br /&gt;
    class StudentNumber(Thing):pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; StudentNumber, FunctionalProperty, InverseFunctionalProperty):pass&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
with onto:&lt;br /&gt;
    class AverageGrade(Grade):pass&lt;br /&gt;
    class hasAverageGrade(Student &amp;gt;&amp;gt; AverageGrade):pass&lt;br /&gt;
Student.is_a.append(hasAverageGrade.exactly(1,AverageGrade))&lt;br /&gt;
Student.is_a.append(hasStudentNumber.exactly(1,StudentNumber))&lt;br /&gt;
    &lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing):pass&lt;br /&gt;
    class BachelorCourse(Course):pass&lt;br /&gt;
    class MasterCourse(Course):pass&lt;br /&gt;
    class PhDCourse(Course):pass&lt;br /&gt;
    &lt;br /&gt;
Course.is_a.append(OneOf([BachelorCourse, MasterCourse, PhDCourse]))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class takesCourse(Student&amp;gt;&amp;gt;Course):pass&lt;br /&gt;
    class BachelorStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(Course)&lt;br /&gt;
        ]&lt;br /&gt;
        &lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class MasterOrBachelorCourse(Course):pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(PhDCourse)) &amp;amp;&lt;br /&gt;
            takesCourse.max(1,BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.some(MasterCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.only(Not(BachelorCourse))&amp;amp;&lt;br /&gt;
            takesCourse.max(2,MasterCourse)&amp;amp;&lt;br /&gt;
            takesCourse.some(PhDCourse)&lt;br /&gt;
            ]&lt;br /&gt;
&lt;br /&gt;
# In comparison to lab 10..&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&lt;br /&gt;
#print(onto2graph(onto).serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;graduate is: &amp;quot;, Graduate.is_a)&lt;br /&gt;
print(&amp;quot;cade is: &amp;quot;, cade.is_a)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative solution. More pro from Andreas, but only a quick draft he stresses (but I still think it&#039;s valuable to share), so you might need to make some changes (like the one recommended above: equivalent_to instead of is_a).&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from owlready2 import get_ontology, Thing, ObjectProperty&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
BASE = &#039;http://info216.uib.no/owlready2-lab/&#039;&lt;br /&gt;
onto = get_ontology(BASE)&lt;br /&gt;
&lt;br /&gt;
def onto2graph(onto):&lt;br /&gt;
    graph = Graph()&lt;br /&gt;
    onto.save(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    graph.parse(&#039;temp.nt&#039;, format=&#039;ntriples&#039;)&lt;br /&gt;
    return graph&lt;br /&gt;
&lt;br /&gt;
def print_onto(onto):&lt;br /&gt;
    g = onto2graph(onto)&lt;br /&gt;
    g.bind(&#039;&#039;, Namespace(BASE))&lt;br /&gt;
    print(g.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
from owlready2 import destroy_entity&lt;br /&gt;
def clean_onto(onto):&lt;br /&gt;
    with onto:&lt;br /&gt;
        for ind in onto.individuals():&lt;br /&gt;
            destroy_entity(ind)&lt;br /&gt;
        for prop in onto.properties():&lt;br /&gt;
            destroy_entity(prop)&lt;br /&gt;
        for cls in onto.classes():&lt;br /&gt;
            destroy_entity(cls)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        is_a = [hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
# anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
with onto:&lt;br /&gt;
    class hasDegree(ObjectProperty): pass&lt;br /&gt;
    class degreeFrom(ObjectProperty): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class University(Thing): pass&lt;br /&gt;
    class UniversityGraduate(Thing): &lt;br /&gt;
        hasDegree: Degree&lt;br /&gt;
        is_a = [hasDegree.some(Degree &amp;amp; degreeFrom.some(University))]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import declare_datatype&lt;br /&gt;
class XSDString(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def str_parser(s): return s&lt;br /&gt;
def str_unparser(s): return s&lt;br /&gt;
declare_datatype(XSDString, &#039;http://www.w3.org/2001/XMLSchema#string&#039;, str_parser, str_unparser)&lt;br /&gt;
&lt;br /&gt;
# a grade is either an A, B, C, D, E or F&lt;br /&gt;
from owlready2 import OneOf&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    grade_C = Grade()&lt;br /&gt;
    grade_C.charGrade = [&#039;C&#039;]&lt;br /&gt;
    grade_D = Grade()&lt;br /&gt;
    grade_D.charGrade = [&#039;D&#039;]&lt;br /&gt;
    grade_E = Grade()&lt;br /&gt;
    grade_E.charGrade = [&#039;E&#039;]&lt;br /&gt;
    grade_F = Grade()&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B, grade_C, grade_D, grade_E, grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a straight A student is a student that has only A grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate has no F grades&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    grade_F.charGrade = [&#039;F&#039;]&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A,  # ...&lt;br /&gt;
        grade_F&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeF(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_F])]&lt;br /&gt;
    class Graduate(Student):&lt;br /&gt;
        equivalent_to = [Student &amp;amp; ~ hasGrade.some(GradeF)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a student has a single unique student number&lt;br /&gt;
class XSDInt(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return int(s)&lt;br /&gt;
def int_unparser(i): return str(i)&lt;br /&gt;
declare_datatype(XSDInt, &#039;http://www.w3.org/2001/XMLSchema#int&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import FunctionalProperty, InverseFunctionalProperty&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasStudentNumber(Student &amp;gt;&amp;gt; XSDInt): &lt;br /&gt;
        is_a = [FunctionalProperty, InverseFunctionalProperty]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# each student has exactly one average grade&lt;br /&gt;
class XSDFloat(object):&lt;br /&gt;
    def __init__(self, value): self.value = value&lt;br /&gt;
def int_parser(s): return float(s)&lt;br /&gt;
def int_unparser(f): return str(f)&lt;br /&gt;
declare_datatype(XSDFloat, &#039;http://www.w3.org/2001/XMLSchema#float&#039;, int_parser, int_unparser)&lt;br /&gt;
&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasAverageGrade(Grade &amp;gt;&amp;gt; XSDFloat): pass&lt;br /&gt;
    Student.is_a.append(hasAverageGrade.exactly(1, XSDFloat))&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# a bachelor student takes only bachelor courses&lt;br /&gt;
from owlready2 import AllDisjoint&lt;br /&gt;
with onto:&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    AllDisjoint([BachelorCourse, MasterCourse, PhDCourse])&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a masters student takes only master courses, except for at most one bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class MasterStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(MasterCourse | BachelorCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(1, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D student takes only Ph.D courses, except for at most two masters courses&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class MasterCourse(Course): pass&lt;br /&gt;
    class PhDCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.some(PhDCourse) &amp;amp;&lt;br /&gt;
            takesCourse.only(PhDCourse | MasterCourse) &amp;amp;&lt;br /&gt;
            takesCourse.max(2, MasterCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a Ph.D. student cannot take a bachelor course&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [&lt;br /&gt;
            takesCourse.max(0, BachelorCourse)&lt;br /&gt;
        ]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
# ...alternative solution&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Course(Thing): pass&lt;br /&gt;
    class takesCourse(Student &amp;gt;&amp;gt; Course): pass&lt;br /&gt;
    class BachelorCourse(Course): pass&lt;br /&gt;
    class PhDStudent(Student):&lt;br /&gt;
        is_a = [Student &amp;amp; ~ takesCourse.some(BachelorCourse)]&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
 # a graduate is a student with at least one degree&lt;br /&gt;
with onto:&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class Degree(Thing): pass&lt;br /&gt;
    class hasDegree(Student &amp;gt;&amp;gt; Degree): pass&lt;br /&gt;
    class Graduate(Student): &lt;br /&gt;
        equivalent_to = [Student &amp;amp; hasDegree.some(Degree)]&lt;br /&gt;
&lt;br /&gt;
 # test with individual&lt;br /&gt;
with onto:&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    infosci = Degree()&lt;br /&gt;
    cade.hasDegree.append(infosci)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.Graduate in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
# if you have more time: &lt;br /&gt;
# populate the ontology with individuals&lt;br /&gt;
# a straight A student is a student that has only A grades&lt;br /&gt;
clean_onto(onto)&lt;br /&gt;
with onto:&lt;br /&gt;
    class Grade(Thing): pass&lt;br /&gt;
    class charGrade(Grade &amp;gt;&amp;gt; XSDString): pass&lt;br /&gt;
    grade_A = Grade()&lt;br /&gt;
    grade_A.charGrade = [&#039;A&#039;]&lt;br /&gt;
    grade_B = Grade()&lt;br /&gt;
    grade_B.charGrade = [&#039;B&#039;]&lt;br /&gt;
    # ...&lt;br /&gt;
    Grade.equivalent_to.append(OneOf([&lt;br /&gt;
        grade_A, grade_B,  # ...&lt;br /&gt;
    ])) &lt;br /&gt;
&lt;br /&gt;
    class Student(Thing): pass&lt;br /&gt;
    class hasGrade(Student &amp;gt;&amp;gt; Grade): pass&lt;br /&gt;
    class GradeA(Grade):&lt;br /&gt;
        equivalent_to = [OneOf([grade_A])]&lt;br /&gt;
    class StraightAStudent(Student):&lt;br /&gt;
        equivalent_to = [&lt;br /&gt;
            Student &amp;amp;&lt;br /&gt;
            hasGrade.some(GradeA) &amp;amp; hasGrade.only(GradeA)&lt;br /&gt;
        ]&lt;br /&gt;
    # add individual&lt;br /&gt;
    cade = Student()&lt;br /&gt;
    cade.hasGrade.append(grade_A)&lt;br /&gt;
print_onto(onto)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import sync_reasoner&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&lt;br /&gt;
from owlready2 import close_world&lt;br /&gt;
close_world(onto)  # because of the &amp;quot;only&amp;quot;-restriction&lt;br /&gt;
sync_reasoner()&lt;br /&gt;
print(onto.StraightAStudent in cade.is_a)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=1866</id>
		<title>Lab: Using Graph Embeddings</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=1866"/>
		<updated>2022-05-04T09:45:45Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: Using Graph Embeddings=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Using knowledge graph embeddings with TorchKGE.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- ==Tutorial== --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
The following TorchKGE classes are central:&lt;br /&gt;
* &#039;&#039;&#039;KnowledgeGraph&#039;&#039;&#039; - contains the knowledge graph (KG)&lt;br /&gt;
* &#039;&#039;&#039;Model&#039;&#039;&#039; - contains the embeddings (entity and relation vectors) for some KG&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Knowledge Graph&#039;&#039;&#039;:&lt;br /&gt;
* Use a [https://torchkge.readthedocs.io/en/latest/reference/utils.html#pre-trained-models dataset loader] to load a KG you want to work with. Freebase FB15k is a good choice. (You will need a pre-trained model for your KG later, to choose one of FB15k, FB15k237, WDV5, WN18RR, or Yago3-10. This lab has mostly been tested on FB15k.)&lt;br /&gt;
* Use the methods provided by the [https://torchkge.readthedocs.io/en/latest/reference/data.html#knowledge-graph KnolwedgeGraph class] to inspect the KG. &lt;br /&gt;
** Print out the numbers of entities, relations, and facts in the training, validation, and testing sets. &lt;br /&gt;
** Print the identifiers for the first 10 entities and relations (&#039;&#039;tip:&#039;&#039; ent2ix and rel2ix).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;External identifiers&#039;&#039;&#039;:&lt;br /&gt;
* Download a dataset that provides more understandable labels for the entities (and perhaps relations) in your KnowledgeGraph&lt;br /&gt;
** If you use FB15k, the relation names are not so bad, but the entity identifiers do not give much meaning. Same with WordNet. [https://github.com/villmow/datasets_knowledge_embedding This repository] contains mappings for the Freebase and WordNet datasets.&lt;br /&gt;
** If you use a Wikidata graph, the entities and relations are all P- and Q-codes. To get labels, you can try a combination of [https://query.wikidata.org/ SPARQL queries] and [https://pypi.org/project/Wikidata/ this API].&lt;br /&gt;
* Create mappings from external label to entity (and perhaps relation) ids in the KnowledgeGraph. Also create the inverse mappings.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Test entities and relations&#039;&#039;&#039;:&lt;br /&gt;
* Get the KG indexes for a few entities and relations. If you use the Freebase or Wikidata graphs, you can try &#039;J. K. Rowling&#039; and &#039;WALL·E&#039; as entities (&#039;&#039;note&#039;&#039; that the dot in &#039;WALL·E&#039; is not a hyphen or usual period.) For relations you can try &#039;influenced by&#039; and &#039;genre&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Model&#039;&#039;&#039;:&lt;br /&gt;
* Load a [https://torchkge.readthedocs.io/en/latest/reference/utils.html#pre-trained-models pre-trained TransE model] that matches your KnowledgeGraph.&lt;br /&gt;
** Print out the numbers of entities, relations, and the dimensions of the entity and relation vectors. Do they match your KnowledgeGraph. &lt;br /&gt;
* Get the vectors for your test entities and relations (for example, &#039;J. K. Rowling&#039; and &#039;influenced by&#039;).&lt;br /&gt;
* Find vectors for a few more entities (both unrelated and related ones, e.g., &#039;J. R. R. Tolkien&#039;, &#039;C. S. Lewis&#039;, ...). Use the [https://torchkge.readthedocs.io/en/latest/reference/models.html#translationalmodels model.dissimilarity()-method] to estimate how semantically close your entities are. Do the distances make sense?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;K-nearest neighbours&#039;&#039;&#039;:&lt;br /&gt;
* Find the indexes of the 10 entity vectors that are nearest neighbours to your entity of choice. You can use [https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html sciKit-learn&#039;s sklearn.neighbors.NearestNeighbors.kneighbors()-method] for this.&lt;br /&gt;
* Map the indexes of the 10-nearest neighbouring entities back into human-understandable labels. Does this make sense? Try the same thing with another entity (e.g., &#039;WALL·E&#039;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Translation&#039;&#039;&#039;:&lt;br /&gt;
* Add together the vectors for an entity and a relation that that gives meaning for the entity (e.g., &#039;J. K. Rowling&#039; - &#039;influenced by&#039;, &#039;WALL·E&#039; - &#039;genre&#039;). Find the 10-nearest neighbouring entities for the vector sum. Does this make sense? Try more entities and relations. Try to find examples that work and that do not work well.&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
!pip install torchkge&lt;br /&gt;
!pip install sklearn&lt;br /&gt;
!git clone https://github.com/villmow/datasets_knowledge_embedding.git&lt;br /&gt;
&lt;br /&gt;
from torchkge.utils.datasets import load_fb15k237&lt;br /&gt;
&lt;br /&gt;
kg_train, kg_val, kg_test = load_fb15k237()&lt;br /&gt;
&lt;br /&gt;
print(list(kg_train.ent2ix.keys())[-10:])&lt;br /&gt;
print(list(kg_train.rel2ix.keys())[-10:])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Download files with human-readable labels for (most) Freebase entities used in the dataset. Labels seem to be missing # for some entities used in FB15k-237.&lt;br /&gt;
import json&lt;br /&gt;
&lt;br /&gt;
TEXT_TRIPLES_DIR = &#039;datasets_knowledge_embedding/FB15k-237/&#039;&lt;br /&gt;
with open(TEXT_TRIPLES_DIR+&#039;entity2wikidata.json&#039;) as file:&lt;br /&gt;
    _entity2wikidata = json.load(file)&lt;br /&gt;
&lt;br /&gt;
 ent2lbl = {&lt;br /&gt;
    ent: wd[&#039;label&#039;]&lt;br /&gt;
    for ent, wd in _entity2wikidata.items()&lt;br /&gt;
}&lt;br /&gt;
lbl2ent = {lbl: ent for ent, lbl in ent2lbl.items()}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print([&lt;br /&gt;
    ent2lbl[ent] &lt;br /&gt;
    for ent in kg_train.ent2ix.keys()&lt;br /&gt;
    if ent in ent2lbl][-10:])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==If You Have More Time==&lt;br /&gt;
&lt;br /&gt;
* Try it out with different datasets, for example one you create youreself using SPARQL queries on an open KG.&lt;br /&gt;
&lt;br /&gt;
==Useful readings==&lt;br /&gt;
* [https://torchkge.readthedocs.io/en/latest/ Welcome to TorchKGE’ s documentation!]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1845</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1845"/>
		<updated>2022-04-21T13:47:49Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
import spotlight&lt;br /&gt;
from spotlight import SpotlightException&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(address=SERVER,text=entity, confidence=CONFIDENCE)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_spotlight = annotate_entity(row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(&lt;br /&gt;
		ex + row[&#039;investigation&#039;] + &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	president_spotlight = annotate_entity(row[&#039;president&#039;])&lt;br /&gt;
&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), RDF.type, sem.Event)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasBeginTimeStamp, investigation_start)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((( URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasEndTimeStamp, investigation_end)))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), tl.duration, investigation_days))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), dbp.president, URIRef(president_spotlight[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, dbp.president, dbr.president_underscore))&lt;br /&gt;
	try:&lt;br /&gt;
		g.add((URIRef(investigation_spotlight[0][&amp;quot;URI&amp;quot;]), sem.hasSubEvent, investigation_result))&lt;br /&gt;
	except:&lt;br /&gt;
		g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
	&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - XML==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# URL of xml data&lt;br /&gt;
url = &#039;http://feeds.bbci.co.uk/news/rss.xml&#039;&lt;br /&gt;
# Retrieve the xml data from the web-url.&lt;br /&gt;
resp = requests.get(url)&lt;br /&gt;
# Creating an ElementTree from the response content&lt;br /&gt;
tree = ET.ElementTree(ET.fromstring(resp.content))&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
# I just realized this is cheating, but whatever, you should do it with xmltree&lt;br /&gt;
writerDict = {&lt;br /&gt;
    &amp;quot;Mon&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Tue&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Wed&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Thu&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Fri&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Sat&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;,&lt;br /&gt;
    &amp;quot;Sun&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
for item in root.findall(&amp;quot;./channel/item&amp;quot;):&lt;br /&gt;
    copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
    News_article_id = URIRef(item.find(&amp;quot;guid&amp;quot;).text)&lt;br /&gt;
    title = Literal(item.find(&amp;quot;title&amp;quot;).text)&lt;br /&gt;
    description = Literal(item.find(&amp;quot;description&amp;quot;).text)&lt;br /&gt;
    link = URIRef(item.find(&amp;quot;link&amp;quot;).text)&lt;br /&gt;
    pubDate = Literal(item.find(&amp;quot;pubDate&amp;quot;).text)&lt;br /&gt;
    writerName = ex[writerDict[pubDate[:3]]]&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.title, title))&lt;br /&gt;
    g.add((News_article_id, ex.description, description))&lt;br /&gt;
    g.add((News_article_id, ex.source_link, link))&lt;br /&gt;
    g.add((News_article_id, ex.pubDate, pubDate))&lt;br /&gt;
    g.add((News_article_id, ex.copyright, copyright))&lt;br /&gt;
    g.add((News_article_id, RDF.type, ex.News_article))&lt;br /&gt;
    g.add((News_article_id, RDF.type, prov.Entity))&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.authoredBy, writerName))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Person))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Agent))&lt;br /&gt;
    g.add((ex.authoredBy, RDF.type, prov.Generation))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 2==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.minCardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.someValuesFrom, ex.University))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Graduate, br]) &lt;br /&gt;
                #[ex.Person, br] also someValueFrom implies a cardinality of at least one so they would be equivalent.&lt;br /&gt;
                #[ex.Person, ex.Graduate, br] would be redundant since intersection is associative. &lt;br /&gt;
g.add((ex.University_graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;), Literal(&amp;quot;F&amp;quot;)])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.grade, RDFS.range, b1))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Student, b1, b2])&lt;br /&gt;
g.add((ex.Straight_A_student, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;)])&lt;br /&gt;
b4 = BNode()&lt;br /&gt;
g.add((b4, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b4, OWL.oneOf, b3))&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b4))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Person, b1, b5]) &lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.average_grade))&lt;br /&gt;
g.add((b1, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.student_number))&lt;br /&gt;
g.add((b2, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
Collection(g, b3, [ex.Person, b1, b2]) &lt;br /&gt;
g.add((ex.Student, OWL.intersectionOf, b3))&lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Bachelor_course, ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
#g.add((b1, RDF.type, OWL.Class))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Course, RDF.type, b1))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
g.add((ex.Bachelor_student, RDFS.subClassOf, ex.Student))&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Student, b1])&lt;br /&gt;
g.add((ex.Bachelor_student, OWL.intersectionOf, b2))&lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(1)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex.Bachelor_course])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex.Master_student, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lab 11: Semantic Lifting - HTML==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs&lt;br /&gt;
from rdflib import Graph, Literal, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF, SKOS, XSD&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Download html from URL and parse it with BeautifulSoup.&lt;br /&gt;
url = &amp;quot;https://www.semanticscholar.org/topic/Knowledge-Graph/159858&amp;quot;&lt;br /&gt;
page = requests.get(url)&lt;br /&gt;
html = bs(page.content, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
# print(html.prettify())&lt;br /&gt;
&lt;br /&gt;
# Find the html that surrounds all the papers&lt;br /&gt;
papers = html.find_all(&#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-container&#039;})&lt;br /&gt;
# Find the html that surrounds the info box&lt;br /&gt;
topic = html.find_all(&lt;br /&gt;
    &#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-item__left-column entity-header&#039;})&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Iterate through each paper to make triples:&lt;br /&gt;
for paper in papers:&lt;br /&gt;
    # e.g selecting title.&lt;br /&gt;
    title = paper.find(&#039;div&#039;, attrs={&#039;class&#039;: &#039;timeline-paper-title&#039;}).text&lt;br /&gt;
    author = paper.find(&#039;span&#039;, attrs={&#039;class&#039;: &#039;author-list&#039;}).text&lt;br /&gt;
    papper_year = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;paper-year&amp;quot;}).text&lt;br /&gt;
    corpus_ID = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;corpus-id&amp;quot;}).text&lt;br /&gt;
    corpus_ID = corpus_ID.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
    c_id = corpus_ID.replace(&amp;quot;Corpus_ID:_&amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
    article = URIRef(ex + c_id)&lt;br /&gt;
&lt;br /&gt;
    # Adding tripels&lt;br /&gt;
    g.add((article, RDF.type, ex.paper))&lt;br /&gt;
    g.add((article, ex.HasID, Literal(c_id, datatype=XSD.int)))&lt;br /&gt;
    g.add((article, ex.HasTitle, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((article, ex.Publisher_year, Literal(papper_year, datatype=XSD.year)))&lt;br /&gt;
&lt;br /&gt;
    author = author.split(&amp;quot;, &amp;quot;)&lt;br /&gt;
    for x in author:&lt;br /&gt;
        name = x.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
        name = URIRef(ex + name)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, ex.hasAuthor, name))&lt;br /&gt;
&lt;br /&gt;
# Iterate through the info box to make triples:&lt;br /&gt;
    for items in topic:&lt;br /&gt;
        main_topic = items.find(&#039;h1&#039;, attrs={&#039;class&#039;: &#039;entity-name&#039;}).text&lt;br /&gt;
        related_topic = items.find(&lt;br /&gt;
            &#039;div&#039;, attrs={&#039;class&#039;: &#039;entity-aliases&#039;}).text&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot;Known as: &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(f&#039;\xa0Expand&#039;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot; &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        main_topic = main_topic.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        main_topic = URIRef(ex + main_topic)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, RDF.type, SKOS.Concept))&lt;br /&gt;
        g.add((article, SKOS.hasTopConcept, main_topic))&lt;br /&gt;
&lt;br /&gt;
    related_topic = related_topic.split(&#039;,&#039;)&lt;br /&gt;
&lt;br /&gt;
    for related_labels in related_topic:&lt;br /&gt;
        related_topic = URIRef(ex + related_labels)&lt;br /&gt;
        g.add((article, SKOS.broader, related_topic))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1844</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1844"/>
		<updated>2022-04-20T13:22:03Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - XML==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# URL of xml data&lt;br /&gt;
url = &#039;http://feeds.bbci.co.uk/news/rss.xml&#039;&lt;br /&gt;
# Retrieve the xml data from the web-url.&lt;br /&gt;
resp = requests.get(url)&lt;br /&gt;
# Creating an ElementTree from the response content&lt;br /&gt;
tree = ET.ElementTree(ET.fromstring(resp.content))&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
# I just realized this is cheating, but whatever, you should do it with xmltree&lt;br /&gt;
writerDict = {&lt;br /&gt;
    &amp;quot;Mon&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Tue&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Wed&amp;quot;:&amp;quot;Thomas_Smith&amp;quot;,&lt;br /&gt;
    &amp;quot;Thu&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Fri&amp;quot;:&amp;quot;Joseph_Olson&amp;quot;,&lt;br /&gt;
    &amp;quot;Sat&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;,&lt;br /&gt;
    &amp;quot;Sun&amp;quot;:&amp;quot;Sophia_Cruise&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
for item in root.findall(&amp;quot;./channel/item&amp;quot;):&lt;br /&gt;
    copyright = Literal(root.findall(&amp;quot;./channel&amp;quot;)[0].find(&amp;quot;copyright&amp;quot;).text)&lt;br /&gt;
&lt;br /&gt;
    News_article_id = URIRef(item.find(&amp;quot;guid&amp;quot;).text)&lt;br /&gt;
    title = Literal(item.find(&amp;quot;title&amp;quot;).text)&lt;br /&gt;
    description = Literal(item.find(&amp;quot;description&amp;quot;).text)&lt;br /&gt;
    link = URIRef(item.find(&amp;quot;link&amp;quot;).text)&lt;br /&gt;
    pubDate = Literal(item.find(&amp;quot;pubDate&amp;quot;).text)&lt;br /&gt;
    writerName = ex[writerDict[pubDate[:3]]]&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.title, title))&lt;br /&gt;
    g.add((News_article_id, ex.description, description))&lt;br /&gt;
    g.add((News_article_id, ex.source_link, link))&lt;br /&gt;
    g.add((News_article_id, ex.pubDate, pubDate))&lt;br /&gt;
    g.add((News_article_id, ex.copyright, copyright))&lt;br /&gt;
    g.add((News_article_id, RDF.type, ex.News_article))&lt;br /&gt;
    g.add((News_article_id, RDF.type, prov.Entity))&lt;br /&gt;
&lt;br /&gt;
    g.add((News_article_id, ex.authoredBy, writerName))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Person))&lt;br /&gt;
    g.add((writerName, RDF.type, prov.Agent))&lt;br /&gt;
    g.add((ex.authoredBy, RDF.type, prov.Generation))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 2==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.minCardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.degree))&lt;br /&gt;
g.add((br, OWL.someValuesFrom, ex.University))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Graduate, br]) &lt;br /&gt;
                #[ex.Person, br] also someValueFrom implies a cardinality of at least one so they would be equivalent.&lt;br /&gt;
                #[ex.Person, ex.Graduate, br] would be redundant since intersection is associative. &lt;br /&gt;
g.add((ex.University_graduate, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a grade is either an A, B, C, D, E or F&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;), Literal(&amp;quot;F&amp;quot;)])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.grade, RDFS.range, b1))&lt;br /&gt;
&lt;br /&gt;
#a straight A student is a student that has only A grades&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, Literal(&amp;quot;A&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Student, b1, b2])&lt;br /&gt;
g.add((ex.Straight_A_student, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
#a graduate has no F grades&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [Literal(&amp;quot;A&amp;quot;), Literal(&amp;quot;B&amp;quot;), Literal(&amp;quot;C&amp;quot;), Literal(&amp;quot;D&amp;quot;), Literal(&amp;quot;E&amp;quot;)])&lt;br /&gt;
b4 = BNode()&lt;br /&gt;
g.add((b4, RDF.type, RDFS.Datatype))&lt;br /&gt;
g.add((b4, OWL.oneOf, b3))&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.grade))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b4))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Person, b1, b5]) &lt;br /&gt;
g.add((ex.Graduate, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a student has a unique student number&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.student_number, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
#each student has exactly one average grade&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.average_grade))&lt;br /&gt;
g.add((b1, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.student_number))&lt;br /&gt;
g.add((b2, OWL.cardinality, Literal(1)))&lt;br /&gt;
&lt;br /&gt;
Collection(g, b3, [ex.Person, b1, b2]) &lt;br /&gt;
g.add((ex.Student, OWL.intersectionOf, b3))&lt;br /&gt;
&lt;br /&gt;
#a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Bachelor_course, ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
#g.add((b1, RDF.type, OWL.Class))&lt;br /&gt;
g.add((b1, OWL.oneOf, bi))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Course, RDF.type, b1))&lt;br /&gt;
&lt;br /&gt;
#a bachelor student takes only bachelor courses&lt;br /&gt;
g.add((ex.Bachelor_student, RDFS.subClassOf, ex.Student))&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.allValuesFrom, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Student, b1])&lt;br /&gt;
g.add((ex.Bachelor_student, OWL.intersectionOf, b2))&lt;br /&gt;
&lt;br /&gt;
#a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(1)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Bachelor_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex.Bachelor_course])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex.Master_student, OWL.intersectionOf, b6))&lt;br /&gt;
&lt;br /&gt;
#a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
g.add((b1, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b1, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b1, OWL.maxQualifiedCardinality, Literal(2)))&lt;br /&gt;
g.add((b1, OWL.onClass, ex.Master_course))&lt;br /&gt;
&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
g.add((b2, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b2, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b2, OWL.someValuesFrom, ex[&amp;quot;Ph.D_course&amp;quot;]))&lt;br /&gt;
&lt;br /&gt;
b3 = BNode()&lt;br /&gt;
Collection(g, b3, [ex.Master_course, ex[&amp;quot;Ph.D_course&amp;quot;]])&lt;br /&gt;
&lt;br /&gt;
b5 = BNode()&lt;br /&gt;
g.add((b5, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((b5, OWL.onProperty, ex.hasCourse))&lt;br /&gt;
g.add((b5, OWL.allValuesFrom, b3))&lt;br /&gt;
&lt;br /&gt;
b6 = BNode()&lt;br /&gt;
Collection(g, b6, [ex.Student, b1, b2, b5])&lt;br /&gt;
g.add((ex[&amp;quot;Ph.D_student&amp;quot;], OWL.intersectionOf, b6))&lt;br /&gt;
#a Ph.D. student cannot take a bachelor course&lt;br /&gt;
    #NA, it&#039;s already true&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lab 11: Semantic Lifting - HTML==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs&lt;br /&gt;
from rdflib import Graph, Literal, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF, SKOS, XSD&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Download html from URL and parse it with BeautifulSoup.&lt;br /&gt;
url = &amp;quot;https://www.semanticscholar.org/topic/Knowledge-Graph/159858&amp;quot;&lt;br /&gt;
page = requests.get(url)&lt;br /&gt;
html = bs(page.content, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
# print(html.prettify())&lt;br /&gt;
&lt;br /&gt;
# Find the html that surrounds all the papers&lt;br /&gt;
papers = html.find_all(&#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-container&#039;})&lt;br /&gt;
# Find the html that surrounds the info box&lt;br /&gt;
topic = html.find_all(&lt;br /&gt;
    &#039;div&#039;, attrs={&#039;class&#039;: &#039;flex-item__left-column entity-header&#039;})&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Iterate through each paper to make triples:&lt;br /&gt;
for paper in papers:&lt;br /&gt;
    # e.g selecting title.&lt;br /&gt;
    title = paper.find(&#039;div&#039;, attrs={&#039;class&#039;: &#039;timeline-paper-title&#039;}).text&lt;br /&gt;
    author = paper.find(&#039;span&#039;, attrs={&#039;class&#039;: &#039;author-list&#039;}).text&lt;br /&gt;
    papper_year = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;paper-year&amp;quot;}).text&lt;br /&gt;
    corpus_ID = paper.find(&lt;br /&gt;
        &#039;li&#039;, attrs={&#039;data-selenium-selector&#039;: &amp;quot;corpus-id&amp;quot;}).text&lt;br /&gt;
    corpus_ID = corpus_ID.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
    c_id = corpus_ID.replace(&amp;quot;Corpus_ID:_&amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
    article = URIRef(ex + c_id)&lt;br /&gt;
&lt;br /&gt;
    # Adding tripels&lt;br /&gt;
    g.add((article, RDF.type, ex.paper))&lt;br /&gt;
    g.add((article, ex.HasID, Literal(c_id, datatype=XSD.int)))&lt;br /&gt;
    g.add((article, ex.HasTitle, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((article, ex.Publisher_year, Literal(papper_year, datatype=XSD.year)))&lt;br /&gt;
&lt;br /&gt;
    author = author.split(&amp;quot;, &amp;quot;)&lt;br /&gt;
    for x in author:&lt;br /&gt;
        name = x.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
        name = URIRef(ex + name)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, ex.hasAuthor, name))&lt;br /&gt;
&lt;br /&gt;
# Iterate through the info box to make triples:&lt;br /&gt;
    for items in topic:&lt;br /&gt;
        main_topic = items.find(&#039;h1&#039;, attrs={&#039;class&#039;: &#039;entity-name&#039;}).text&lt;br /&gt;
        related_topic = items.find(&lt;br /&gt;
            &#039;div&#039;, attrs={&#039;class&#039;: &#039;entity-aliases&#039;}).text&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot;Known as: &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(f&#039;\xa0Expand&#039;, &amp;quot;&amp;quot;)&lt;br /&gt;
        related_topic = related_topic.replace(&amp;quot; &amp;quot;, &amp;quot;&amp;quot;)&lt;br /&gt;
        main_topic = main_topic.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        main_topic = URIRef(ex + main_topic)&lt;br /&gt;
&lt;br /&gt;
        g.add((article, RDF.type, SKOS.Concept))&lt;br /&gt;
        g.add((article, SKOS.hasTopConcept, main_topic))&lt;br /&gt;
&lt;br /&gt;
    related_topic = related_topic.split(&#039;,&#039;)&lt;br /&gt;
&lt;br /&gt;
    for related_labels in related_topic:&lt;br /&gt;
        related_topic = URIRef(ex + related_labels)&lt;br /&gt;
        g.add((article, SKOS.broader, related_topic))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1797</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1797"/>
		<updated>2022-03-24T13:20:07Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDFS.subPropertyOf, ex.postalcode))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1796</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1796"/>
		<updated>2022-03-24T13:12:41Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL 1==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
print()&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;lab8turtle.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Cade and Emma are two different persons. &lt;br /&gt;
g.add((ex.Cade, OWL.differentFrom, ex.Emma))&lt;br /&gt;
# The country USA above is the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames resource http://sws.geonames.org/6252001/ (gn:6252001). &lt;br /&gt;
g.add((ex.USA, OWL.sameAs, dbp.United_States))&lt;br /&gt;
g.add((ex.USA, OWL.sameAs, geo[&amp;quot;6252001&amp;quot;]))&lt;br /&gt;
# The person class (the RDF type the Cade and Emma resources) in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes &lt;br /&gt;
    # (they are http://xmlns.com/foaf/0.1/Person, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. &lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, schema.Person))&lt;br /&gt;
g.add((FOAF.Person, OWL.sameAs, akt.Person))&lt;br /&gt;
# Nothing can be any two of a person, a university, or a city at the same time. &lt;br /&gt;
Collection(g, ex.DisjointClasses, [FOAF.Person, ex.University, ex.City])&lt;br /&gt;
g.add((OWL.AllDifferent, OWL.distinctMembers, ex.DisjointClasses))&lt;br /&gt;
# The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US &lt;br /&gt;
    # is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). &lt;br /&gt;
g.add((ex.postalCode, RDFS.subPropertyOf, vcard[&amp;quot;postal-code&amp;quot;]))&lt;br /&gt;
# No two US cities can have the same postal code. &lt;br /&gt;
    # We have to add a relation from city to postal code first&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX RDF: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?usa_city ex:us_city_postal_code ?postalcode}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?address RDF:type ex:Address .&lt;br /&gt;
        ?address ex:country ex:USA .&lt;br /&gt;
        ?address ex:city ?usa_city .&lt;br /&gt;
        ?address ex:postalCode ?postalcode&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
    # Now we can make us cities have distinct postal codes&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.us_city_postal_code, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
&lt;br /&gt;
# The property you have used for Emma living in Valencia is the same property as FOAF&#039;s based-near property &lt;br /&gt;
    # (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property (http://dbpedia.org/ontology/hometown, dbo:hometown). &lt;br /&gt;
g.add((ex.city, OWL.sameAs, FOAF.based_near))&lt;br /&gt;
g.add((ex.city, OWL.inverseOf, dbp.hometown))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: &lt;br /&gt;
    # a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.InverseFunctionalProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;lab8output.xml&amp;quot;,format=&amp;quot;xml&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=1774</id>
		<title>Lab: OWL 1</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=1774"/>
		<updated>2022-03-15T12:07:18Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Lab 8: OWL 1 (&amp;quot;RDFS Plus / Basic OWL&amp;quot;)=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Basic OWL ontology programming with RDFlib and owlrl.&lt;br /&gt;
&lt;br /&gt;
WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
RDF and RDFS might be relevant too.&lt;br /&gt;
&lt;br /&gt;
==Classes/Vocabularies==&lt;br /&gt;
&lt;br /&gt;
Vocabulary:&lt;br /&gt;
* OWL (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* OWL (SymmetricProperty, AsymmetricProperty, ReflexiveProperty, IrreflexiveProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty, AllDifferent)&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task 1&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Write OWL triples that corresponds to the following text. &#039;&#039;&#039;.If you can, try to build on your example from labs 2 and 7, or extend the triples at the bottom of the page. OWL can be imported from rdflib.namespace.&lt;br /&gt;
&lt;br /&gt;
Cade and Emma are two different persons. &amp;lt;!-- All the countries mentioned above are different. --&amp;gt; The country USA above is&lt;br /&gt;
the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames&lt;br /&gt;
resource http://sws.geonames.org/6252001/ (gn:6252001). The person class (the RDF type the Cade and Emma resources)&lt;br /&gt;
in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes (they are http://xmlns.com/foaf/0.1/Person,&lt;br /&gt;
http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. Nothing can be any two of a person, a university, or a city at the same time. The property&lt;br /&gt;
you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is&lt;br /&gt;
a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can&lt;br /&gt;
have the same postal code. The property you have used for Emma living in Valencia is the same property as FOAF&#039;s&lt;br /&gt;
based near-property (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property&lt;br /&gt;
(http://dbpedia.org/ontology/hometown, dbo:hometown). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the&lt;br /&gt;
inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task 2&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
e.g&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task 3&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Print/Serialize the ontology. Then use owlrl like seen below to infer additional triples. Can you spot the many inferences?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally write the ontology to a XML file, and try to visualise it using https://service.tib.eu/webvowl/. WebVOWL is oriented towards visualising classes and their properties, so the individuals may not show.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/File:S06-OWL-1.pdf Lecture Notes]&lt;br /&gt;
&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples#RDFS_Plus_.2F_OWL_inference_with_RDFLib Example page]&lt;br /&gt;
&lt;br /&gt;
==Triples you can extend for the tasks==&lt;br /&gt;
&#039;&#039;&#039;Python&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# RDFS Tasks from last time.&lt;br /&gt;
g.add((ex.Cade, ex.degreeFrom, ex.University_of_California))&lt;br /&gt;
g.add((ex.Emma, ex.degreeFrom, ex.University_of_Valencia))&lt;br /&gt;
g.add((ex.Cade, ex.degreeSubject, ex.Biology))&lt;br /&gt;
g.add((ex.Emma, ex.degreeSubject, ex.Chemistry))&lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_Education_Institution))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.Subject))&lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.degreeSubject, RDFS.subPropertyOf, ex.expertise))&lt;br /&gt;
g.add((ex.graduated, RDFS.range, ex.Higher_Education_Institution))&lt;br /&gt;
g.add((ex.graduated, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.degreeFrom, RDFS.subPropertyOf, ex.graduated))&lt;br /&gt;
g.add((ex.Biology, RDFS.label, Literal(&amp;quot;Biology&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.Biology, RDFS.label, Literal(&amp;quot;La Biologie&amp;quot;, lang=&amp;quot;fr&amp;quot;)))&lt;br /&gt;
g.add((ex.Biology, RDFS.comment, Literal(&amp;quot;Biology is a natural science concerned with the study of life and living organisms, including their structure, function, growth, evolution, distribution, identification and taxonomy.&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.label, Literal(&amp;quot;Chemistry&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.label, Literal(&amp;quot;La Chimie&amp;quot;, lang=&amp;quot;fr&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.comment, Literal(&amp;quot;Chemistry is a branch of physical science that studies the composition, structure, properties and change of matter.&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Write OWL triples here&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Turtle&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Cade ex:degreeFrom ex:University_of_California ;&lt;br /&gt;
    ex:degreeSubject ex:Biology .&lt;br /&gt;
&lt;br /&gt;
ex:Emma ex:degreeFrom ex:University_of_Valencia ;&lt;br /&gt;
    ex:degreeSubject ex:Chemistry .&lt;br /&gt;
&lt;br /&gt;
ex:degreeFrom rdfs:subPropertyOf ex:graduated .&lt;br /&gt;
&lt;br /&gt;
ex:degreeSubject rdfs:subPropertyOf ex:expertise .&lt;br /&gt;
&lt;br /&gt;
ex:Biology rdfs:label &amp;quot;Biology&amp;quot;@en,&lt;br /&gt;
        &amp;quot;La Biologie&amp;quot;@fr ;&lt;br /&gt;
    rdfs:comment &amp;quot;Biology is a natural science concerned with the study of life and living organisms, including their structure, function, growth, evolution, distribution, identification and taxonomy.&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
ex:Chemistry rdfs:label &amp;quot;Chemistry&amp;quot;@en,&lt;br /&gt;
        &amp;quot;La Chimie&amp;quot;@fr ;&lt;br /&gt;
    rdfs:comment &amp;quot;Chemistry is a branch of physical science that studies the composition, structure, properties and change of matter.&amp;quot;@en .&lt;br /&gt;
&lt;br /&gt;
ex:University_of_California a ex:University .&lt;br /&gt;
&lt;br /&gt;
ex:University_of_Valencia a ex:University .&lt;br /&gt;
&lt;br /&gt;
ex:expertise rdfs:domain &amp;lt;http://xmlns.com/foaf/0.1/Person&amp;gt; ;&lt;br /&gt;
    rdfs:range ex:Subject .&lt;br /&gt;
&lt;br /&gt;
ex:graduated rdfs:domain &amp;lt;http://xmlns.com/foaf/0.1/Person&amp;gt; ;&lt;br /&gt;
    rdfs:range ex:Higher_Education_Institution .&lt;br /&gt;
&lt;br /&gt;
ex:University rdfs:subClassOf ex:Higher_Education_Institution .&lt;br /&gt;
&lt;br /&gt;
ex:Cade a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Berkeley ;&lt;br /&gt;
            ex:country ex:USA ;&lt;br /&gt;
            ex:postalCode &amp;quot;94709&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;1516_Henry_Street&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 27 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Biology ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Bachelor&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_California ;&lt;br /&gt;
            ex:year &amp;quot;2011-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:interest ex:Bird,&lt;br /&gt;
        ex:Ecology,&lt;br /&gt;
        ex:Environmentalism,&lt;br /&gt;
        ex:Photography,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:married ex:Mary ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ex:Canada,&lt;br /&gt;
        ex:France,&lt;br /&gt;
        ex:Germany ;&lt;br /&gt;
    foaf:knows ex:Emma ;&lt;br /&gt;
    ex:name &amp;quot;Cade_Tracey&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Mary a ex:Student;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:interest ex:Biology,&lt;br /&gt;
        ex:Chocolate,&lt;br /&gt;
        ex:Hiking .&lt;br /&gt;
&lt;br /&gt;
ex:Emma a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valencia ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46020&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:street &amp;quot;Carrer_de_la Guardia_Civil_20&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Chemistry ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2015-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Air_Pollution,&lt;br /&gt;
        ex:Toxic_Waste,&lt;br /&gt;
        ex:Waste_Management,&lt;br /&gt;
        ex:Bananas ;&lt;br /&gt;
    ex:interest ex:Bike_Riding,&lt;br /&gt;
        ex:Music,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ( ex:Portugal ex:Italy ex:France ex:Germany ex:Denmark ex:Sweden ) ;&lt;br /&gt;
    ex:name &amp;quot;Emma_Dominguez&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Meeting1 a ex:Meeting ;&lt;br /&gt;
    ex:date &amp;quot;August, 2014&amp;quot;^^xsd:string ;&lt;br /&gt;
    ex:involved ex:Cade,&lt;br /&gt;
        ex:Emma ;&lt;br /&gt;
    ex:location ex:Paris .&lt;br /&gt;
&lt;br /&gt;
ex:Paris a ex:City ;&lt;br /&gt;
    ex:capitalOf ex:France ;&lt;br /&gt;
    ex:locatedIn ex:France .&lt;br /&gt;
&lt;br /&gt;
ex:France ex:capital ex:Paris .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=1773</id>
		<title>Lab: OWL 1</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=1773"/>
		<updated>2022-03-15T09:20:49Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Lab 8: OWL 1 (&amp;quot;RDFS Plus / Basic OWL&amp;quot;)=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Basic OWL ontology programming with RDFlib and owlrl.&lt;br /&gt;
&lt;br /&gt;
WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
RDF and RDFS might be relevant too.&lt;br /&gt;
&lt;br /&gt;
==Classes/Vocabularies==&lt;br /&gt;
&lt;br /&gt;
Vocabulary:&lt;br /&gt;
* OWL (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* OWL (SymmetricProperty, AsymmetricProperty, ReflexiveProperty, IrreflexiveProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty, AllDifferent)&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task 1&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Write OWL triples that corresponds to the following text. &#039;&#039;&#039;.If you can, try to build on your example from labs 2 and 7, or extend the triples at the bottom of the page. OWL can be imported from rdflib.namespace.&lt;br /&gt;
&lt;br /&gt;
Cade and Emma are two different persons. &amp;lt;!-- All the countries mentioned above are different. --&amp;gt; The country USA above is&lt;br /&gt;
the same as the DBpedia resource http://dbpedia.org/resource/United_States (dbr:United_States) and the GeoNames&lt;br /&gt;
resource http://sws.geonames.org/6252001/ (gn:6252001). The person class (the RDF type the Cade and Emma resources)&lt;br /&gt;
in your graph is the same as FOAF&#039;s, schema.org&#039;s and AKT&#039;s person classes (they are http://xmlns.com/foaf/0.1/Person,&lt;br /&gt;
http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively. Nothing can be any two of a person, a university, or a city at the same time. The property&lt;br /&gt;
you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is&lt;br /&gt;
a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can&lt;br /&gt;
have the same postal code. The property you have used for Emma living in Valencia is the same property as FOAF&#039;s&lt;br /&gt;
based near-property (http://xmlns.com/foaf/0.1/based_near), and it is the inverse of DBpedia&#039;s hometown property&lt;br /&gt;
(http://dbpedia.org/ontology/hometown, dbo:hometown). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the&lt;br /&gt;
inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task 2&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.livesWith, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, ex.sibling, ex.Andrew))&lt;br /&gt;
g.add((ex.Cade, ex.hasFather, ex.Bob))&lt;br /&gt;
g.add((ex.Bob, ex.fatherOf, ex.Cade))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Look through the predicates(properties) above and add new triples for each one that describes them as any of the following: a reflexive , irreflexive, symmetric, asymmetric, transitive, functional, or an Inverse Functional Property.&lt;br /&gt;
e.g&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task 3&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Print/Serialize the ontology. Then use owlrl like seen below to infer additional triples. Can you spot the many inferences?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# These three lines add inferred triples to the graph.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally write the ontology to a TURTLE file, and try to visualise it using http://visualdataweb.de/webvowl/ . WebVOWL is oriented towards visualising classes and their properties, so the individuals may not show.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/File:S06-OWL-1.pdf Lecture Notes]&lt;br /&gt;
&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples#RDFS_Plus_.2F_OWL_inference_with_RDFLib Example page]&lt;br /&gt;
&lt;br /&gt;
==Triples you can extend for the tasks==&lt;br /&gt;
&#039;&#039;&#039;Python&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, FOAF, OWL&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Namespaces&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://sws.geonames.org/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
akt = Namespace(&amp;quot;http://www.aktors.org/ontology/portal#&amp;quot;)&lt;br /&gt;
vcard = Namespace(&amp;quot;http://www.w3.org/2006/vcard/ns#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# RDFS Tasks from last time.&lt;br /&gt;
g.add((ex.Cade, ex.degreeFrom, ex.University_of_California))&lt;br /&gt;
g.add((ex.Emma, ex.degreeFrom, ex.University_of_Valencia))&lt;br /&gt;
g.add((ex.Cade, ex.degreeSubject, ex.Biology))&lt;br /&gt;
g.add((ex.Emma, ex.degreeSubject, ex.Chemistry))&lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_Education_Institution))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.Subject))&lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.degreeSubject, RDFS.subPropertyOf, ex.expertise))&lt;br /&gt;
g.add((ex.graduated, RDFS.range, ex.Higher_Education_Institution))&lt;br /&gt;
g.add((ex.graduated, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.degreeFrom, RDFS.subPropertyOf, ex.graduated))&lt;br /&gt;
g.add((ex.Biology, RDFS.label, Literal(&amp;quot;Biology&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.Biology, RDFS.label, Literal(&amp;quot;La Biologie&amp;quot;, lang=&amp;quot;fr&amp;quot;)))&lt;br /&gt;
g.add((ex.Biology, RDFS.comment, Literal(&amp;quot;Biology is a natural science concerned with the study of life and living organisms, including their structure, function, growth, evolution, distribution, identification and taxonomy.&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.label, Literal(&amp;quot;Chemistry&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.label, Literal(&amp;quot;La Chimie&amp;quot;, lang=&amp;quot;fr&amp;quot;)))&lt;br /&gt;
g.add((ex.Chemistry, RDFS.comment, Literal(&amp;quot;Chemistry is a branch of physical science that studies the composition, structure, properties and change of matter.&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Write OWL triples here&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Turtle&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Cade ex:degreeFrom ex:University_of_California ;&lt;br /&gt;
    ex:degreeSubject ex:Biology .&lt;br /&gt;
&lt;br /&gt;
ex:Emma ex:degreeFrom ex:University_of_Valencia ;&lt;br /&gt;
    ex:degreeSubject ex:Chemistry .&lt;br /&gt;
&lt;br /&gt;
ex:degreeFrom rdfs:subPropertyOf ex:graduated .&lt;br /&gt;
&lt;br /&gt;
ex:degreeSubject rdfs:subPropertyOf ex:expertise .&lt;br /&gt;
&lt;br /&gt;
ex:Biology rdfs:label &amp;quot;Biology&amp;quot;@en,&lt;br /&gt;
        &amp;quot;La Biologie&amp;quot;@fr ;&lt;br /&gt;
    rdfs:comment &amp;quot;Biology is a natural science concerned with the study of life and living organisms, including their structure, function, growth, evolution, distribution, identification and taxonomy.&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
ex:Chemistry rdfs:label &amp;quot;Chemistry&amp;quot;@en,&lt;br /&gt;
        &amp;quot;La Chimie&amp;quot;@fr ;&lt;br /&gt;
    rdfs:comment &amp;quot;Chemistry is a branch of physical science that studies the composition, structure, properties and change of matter.&amp;quot;@en .&lt;br /&gt;
&lt;br /&gt;
ex:University_of_California a ex:University .&lt;br /&gt;
&lt;br /&gt;
ex:University_of_Valencia a ex:University .&lt;br /&gt;
&lt;br /&gt;
ex:expertise rdfs:domain &amp;lt;http://xmlns.com/foaf/0.1/Person&amp;gt; ;&lt;br /&gt;
    rdfs:range ex:Subject .&lt;br /&gt;
&lt;br /&gt;
ex:graduated rdfs:domain &amp;lt;http://xmlns.com/foaf/0.1/Person&amp;gt; ;&lt;br /&gt;
    rdfs:range ex:Higher_Education_Institution .&lt;br /&gt;
&lt;br /&gt;
ex:University rdfs:subClassOf ex:Higher_Education_Institution .&lt;br /&gt;
&lt;br /&gt;
ex:Cade a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Berkeley ;&lt;br /&gt;
            ex:country ex:USA ;&lt;br /&gt;
            ex:postalCode &amp;quot;94709&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;1516_Henry_Street&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 27 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Biology ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Bachelor&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_California ;&lt;br /&gt;
            ex:year &amp;quot;2011-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:interest ex:Bird,&lt;br /&gt;
        ex:Ecology,&lt;br /&gt;
        ex:Environmentalism,&lt;br /&gt;
        ex:Photography,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:married ex:Mary ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ex:Canada,&lt;br /&gt;
        ex:France,&lt;br /&gt;
        ex:Germany ;&lt;br /&gt;
    foaf:knows ex:Emma ;&lt;br /&gt;
    ex:name &amp;quot;Cade_Tracey&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Mary a ex:Student;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:interest ex:Biology,&lt;br /&gt;
        ex:Chocolate,&lt;br /&gt;
        ex:Hiking .&lt;br /&gt;
&lt;br /&gt;
ex:Emma a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valencia ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46020&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:street &amp;quot;Carrer_de_la Guardia_Civil_20&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Chemistry ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2015-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Air_Pollution,&lt;br /&gt;
        ex:Toxic_Waste,&lt;br /&gt;
        ex:Waste_Management,&lt;br /&gt;
        ex:Bananas ;&lt;br /&gt;
    ex:interest ex:Bike_Riding,&lt;br /&gt;
        ex:Music,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ( ex:Portugal ex:Italy ex:France ex:Germany ex:Denmark ex:Sweden ) ;&lt;br /&gt;
    ex:name &amp;quot;Emma_Dominguez&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Meeting1 a ex:Meeting ;&lt;br /&gt;
    ex:date &amp;quot;August, 2014&amp;quot;^^xsd:string ;&lt;br /&gt;
    ex:involved ex:Cade,&lt;br /&gt;
        ex:Emma ;&lt;br /&gt;
    ex:location ex:Paris .&lt;br /&gt;
&lt;br /&gt;
ex:Paris a ex:City ;&lt;br /&gt;
    ex:capitalOf ex:France ;&lt;br /&gt;
    ex:locatedIn ex:France .&lt;br /&gt;
&lt;br /&gt;
ex:France ex:capital ex:Paris .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1770</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1770"/>
		<updated>2022-03-11T14:57:03Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need complex OWL or easy sparql.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 ex:haveMet ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:involved ?person2 .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    #we don&#039;t need to add that people have met themselves&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab for the same reason.&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person ex:hasVisited ?place}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:meeting ?Meeting .&lt;br /&gt;
        ?Meeting ex:location ?place .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for triplet in res:&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_RDFS&amp;diff=1769</id>
		<title>Lab: RDFS</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_RDFS&amp;diff=1769"/>
		<updated>2022-03-10T14:03:11Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 7: RDFS Programming with rdflib and owlrl=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Basic RDFS graph programming in RDFlib.&lt;br /&gt;
Entailments and axioms with owlrl.&lt;br /&gt;
&lt;br /&gt;
==Classes/Methods/Vocabularies==&lt;br /&gt;
owlrl.RDFSClosure (RDFS_Semantics, closure, flush_stored_triples)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Vocabularies: &#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
RDF.type&lt;br /&gt;
&lt;br /&gt;
RDFS.subClassOf, RDFS.subPropertyOf, RDFS.domain, RDFS.range, RDFS.label, RDFS.comment, &lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
First, pip install owlrl.&lt;br /&gt;
The RDFS Vocabulary can be imported from rdflib.namespace, just like FOAF or RDF.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Consider the following Scenario:&#039;&#039;&#039;&lt;br /&gt;
&amp;quot;University of California and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education institutions (HEIs). Only persons can have an expertise, and what they have expertise in is always a subject. Only persons can graduate from a HEI. If you are a student, you are in fact a person as well. That a person is married to someone, means that they know them. Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Create RDFS triples corresponding to the text above with RDFlib&#039;&#039;&#039; - if you can, try to build on&lt;br /&gt;
your example from lab 2! &lt;br /&gt;
&lt;br /&gt;
To create the graph in python, you can just use the g.add syntax as we have done previously, or you can use the following code sample to parse a file into a graph:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Create the graph&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Parse input data into the graph, format is dependent on the file format. Here turtle (ttl). And location is the path to the local file&lt;br /&gt;
g.parse(location=&amp;quot;input.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using these three lines we can add automatically the inferred triples (like ex:University rdf:type ex:Higher_Education_Institute) :&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After you have done this, try to add the following scenario to you graph as well:&lt;br /&gt;
&amp;quot;Having a degree from a HEI means that you have also graduated from that HEI. That a city is a capital of a country means that this city is located in that country. That someone was involved in a meeting, means that they have met the other participants. If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
To do this, you will have to swap out the line&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
with&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
As last two sentences require more advanced reasoning with OWL. Or you can use what we already learned: g.query(), CONSTRUCT the relevant triples, and add them to the graph.&lt;br /&gt;
&lt;br /&gt;
Check that simple inference works -  make sure that your graph contains triples like these, even if&lt;br /&gt;
you have not asserted them explicitly:&lt;br /&gt;
* that University of California and Valencia are HEIs&lt;br /&gt;
* that Cade, Emma, and Mary are all persons&lt;br /&gt;
* that Cade and Emma have both graduated from some HEI&lt;br /&gt;
* that Cade knows Mary&lt;br /&gt;
&lt;br /&gt;
One way to check if the triples are there:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
universities = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:University_of_California rdf:type ex:Higher_Education_Institution.&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(bool(universities))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rewrite some of your existing code to use rdfs:label in a triple and add an rdfs:comment to the same resource.&lt;br /&gt;
&lt;br /&gt;
==If you have more time...==&lt;br /&gt;
Create a new RDFS graph that wraps an empty graph. This graph contains only RDFS axioms. Write it out in Turtle and check that you understand  the meaning and purpose of each axiom.&lt;br /&gt;
&lt;br /&gt;
Create an RDF (not RDFS) graph that contains all the triples in your first graph (the one with all the people and universities). Subtract all the triples in the axiom graph from the people/university graph. Write it out to see that you are left with only the asserted and entailed triples and that none of the axioms remain.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- Download the SKOS vocabulary from https://www.w3.org/2009/08/skos-reference/skos.rdf and save it to a file called, e.g., SKOS.rdf .&lt;br /&gt;
Use the schemagen tool (it is inside your Jena folders, for example under apache-jena-3.1.1/bin) to generate a Java class for the SKOS vocabulary. &lt;br /&gt;
You need to do this from a console window, using a command like &amp;quot;&amp;lt;path&amp;gt;/schemagen -i &amp;lt;infile.rdf&amp;gt; -o &amp;lt;outfile.java&amp;gt;&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Copy the SKOS.java file into your project in the same package as your other Java files,  and try to use SKOS properties &lt;br /&gt;
where they fit, for example to organise the keywords for interests and expertise.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Useful Readings==&lt;br /&gt;
*[https://wiki.uib.no/info216/index.php/File:S05-RDFS-11.pdf Lecture Notes]&lt;br /&gt;
*[https://wiki.uib.no/info216/index.php/Python_Examples Example page]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1768</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1768"/>
		<updated>2022-03-10T13:33:15Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More miscellaneous examples=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1767</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1767"/>
		<updated>2022-03-10T13:31:22Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More examples from past semesters that may be useful=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1766</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1766"/>
		<updated>2022-03-10T13:30:10Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=More examples from past semesters that may be useful=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1765</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1765"/>
		<updated>2022-03-10T13:27:34Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD, RDFS&lt;br /&gt;
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD, OWL&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
g.parse(location=&amp;quot;exampleTTL.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# University of California and University of Valencia are both Universities. &lt;br /&gt;
g.add((ex.University_of_California, RDF.type, ex.University))&lt;br /&gt;
g.add((ex.University_of_Valencia, RDF.type, ex.University))&lt;br /&gt;
# All universities are higher education institutions (HEIs). &lt;br /&gt;
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))&lt;br /&gt;
# Only persons can have an expertise, and what they have expertise in is always a subject. &lt;br /&gt;
g.add((ex.expertise, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.expertise, RDFS.range, ex.subject))&lt;br /&gt;
# Only persons can graduate from a HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))&lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))&lt;br /&gt;
# If you are a student, you are in fact a person as well. &lt;br /&gt;
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
# That a person is married to someone, means that they know them. &lt;br /&gt;
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))&lt;br /&gt;
# Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))&lt;br /&gt;
&lt;br /&gt;
# Having a degree from a HEI means that you have also graduated from that HEI. &lt;br /&gt;
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))&lt;br /&gt;
# That a city is a capital of a country means that this city is located in that country. &lt;br /&gt;
g.add((ex.capital, RDFS.domain, ex.Country))&lt;br /&gt;
g.add((ex.capital, RDFS.range, ex.City))&lt;br /&gt;
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))&lt;br /&gt;
# That someone was involved in a meeting, means that they have met the other participants. &lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
# If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
    # This question was bad for the RDFS lab because we need OWL&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1764</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1764"/>
		<updated>2022-03-10T13:22:45Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; &lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#select all triplets in graph&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
#select the interestes of Cade&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
#select the country and city where Emma lives&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
#select the people who are over 26 years old&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
#select people who graduated with Bachelor&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
# delete cades photography interest&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
&lt;br /&gt;
# delete and insert university of valencia&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
#check if the deletion worked&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	} &lt;br /&gt;
#describe sergio&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1763</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1763"/>
		<updated>2022-03-10T13:20:54Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/property/&amp;quot;)&lt;br /&gt;
dbpage = Namespace(&amp;quot;https://dbpedia.org/page/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;dbpage&amp;quot;, dbpage)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;russia-investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	investigation = URIRef(ex + row[&#039;investigation&#039;])&lt;br /&gt;
	investigation_start = Literal(row[&#039;investigation-start&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_end = Literal(row[&#039;investigation-end&#039;], datatype=XSD.date)&lt;br /&gt;
	investigation_days = Literal(row[&#039;investigation-days&#039;], datatype=XSD.integer)&lt;br /&gt;
&lt;br /&gt;
	name = Literal(row[&#039;name&#039;], datatype=XSD.string)&lt;br /&gt;
	name_underscore = URIRef(dbpage + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	investigation_result = URIRef(ex + row[&#039;investigation&#039;]+ &amp;quot;_investigation_&amp;quot; + row[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	indictment_days = Literal(row[&#039;indictment-days&#039;], datatype=XSD.integer)&lt;br /&gt;
	type = URIRef(dbr + row[&#039;type&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
	cp_date = Literal(row[&#039;cp-date&#039;], datatype=XSD.date)&lt;br /&gt;
	cp_days = Literal(row[&#039;cp-days&#039;], datatype=XSD.duration)&lt;br /&gt;
	overturned = Literal(row[&#039;overturned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	pardoned = Literal(row[&#039;pardoned&#039;], datatype=XSD.boolean)&lt;br /&gt;
	american = Literal(row[&#039;american&#039;], datatype=XSD.boolean)&lt;br /&gt;
	president = Literal(row[&#039;president&#039;], datatype=XSD.string)&lt;br /&gt;
	president_underscore = URIRef(dbr + row[&#039;president&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
	g.add((investigation, sem.hasBeginTimeStamp, investigation_start))&lt;br /&gt;
	g.add((investigation, sem.hasEndTimeStamp, investigation_end))&lt;br /&gt;
	g.add((investigation, tl.duration, investigation_days))&lt;br /&gt;
	g.add((investigation, dbp.president, president_underscore))&lt;br /&gt;
	g.add((investigation, sem.hasSubEvent, investigation_result))&lt;br /&gt;
&lt;br /&gt;
	g.add((investigation_result, ex.resultType, type))&lt;br /&gt;
	g.add((investigation_result, ex.objectOfInvestigation, name_underscore))&lt;br /&gt;
	g.add((investigation_result, ex.isAmerican, american))&lt;br /&gt;
	g.add((investigation_result, ex.indictmentDuration, indictment_days))&lt;br /&gt;
	g.add((investigation_result, ex.caseSolved, cp_date))&lt;br /&gt;
	g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))&lt;br /&gt;
	g.add((investigation_result, ex.overturned, overturned))&lt;br /&gt;
	g.add((investigation_result, ex.pardoned, pardoned))&lt;br /&gt;
	&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;,format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1762</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1762"/>
		<updated>2022-03-10T13:17:23Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, XSD, FOAF&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&lt;br /&gt;
address = BNode()&lt;br /&gt;
degree = BNode()&lt;br /&gt;
&lt;br /&gt;
# from lab 1&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.Characterostic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
g.add((ex.Cade, schema.address, address))&lt;br /&gt;
&lt;br /&gt;
# BNode address&lt;br /&gt;
g.add((address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((address, schema.streetAddress, Literal(&#039;1516 Henry Street&#039;)))&lt;br /&gt;
g.add((address, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((address, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((address, schema.postalCode, Literal(&#039;94709&#039;)))&lt;br /&gt;
g.add((address, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
# More info about Cade&lt;br /&gt;
g.add((ex.Cade, ex.Degree, degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Biology))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Bachelors_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_California))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2001&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Emma&lt;br /&gt;
emma_degree = BNode()&lt;br /&gt;
g.add((ex.Emma, FOAF.name, Literal(&amp;quot;Emma Dominguez&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Emma, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Emma, ex.Degree, emma_degree))&lt;br /&gt;
g.add((degree, ex.Field, dbp.Chemistry))&lt;br /&gt;
g.add((degree, RDF.type, dbp.Masters_degree))&lt;br /&gt;
g.add((degree, ex.Universety, dbp.University_of_Valencia))&lt;br /&gt;
g.add((degree, ex.year, Literal(&#039;2015&#039;, datatype=XSD.gYear)))&lt;br /&gt;
&lt;br /&gt;
# Address&lt;br /&gt;
emma_address = BNode()&lt;br /&gt;
g.add((ex.Emma, schema.address, emma_address))&lt;br /&gt;
g.add((emma_address, RDF.type, schema.PostalAdress))&lt;br /&gt;
g.add((emma_address, schema.streetAddress,&lt;br /&gt;
       Literal(&#039;Carrer de la Guardia Civil 20&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressRegion, dbp.Valencia))&lt;br /&gt;
g.add((emma_address, schema.postalCode, Literal(&#039;46020&#039;)))&lt;br /&gt;
g.add((emma_address, schema.addressCountry, dbp.Spain))&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
           [dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1760</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1760"/>
		<updated>2022-03-10T13:14:36Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;lab4&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://10.111.21.183:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Print Emmas city and country&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Emma ex:address ?address .&lt;br /&gt;
        ?address ex:city ?emmaCity .&lt;br /&gt;
        ?address ex:country ?emmaCountry .&lt;br /&gt;
        } &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;Emma&#039;s city is &amp;quot;+result[&amp;quot;emmaCity&amp;quot;][&amp;quot;value&amp;quot;]+&amp;quot; and Emma&#039;s country is &amp;quot; + result[&amp;quot;emmaCountry&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select the people who are over 26 years old&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?age&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:age ?age .&lt;br /&gt;
        FILTER(?age &amp;gt; 26) .  &lt;br /&gt;
        }&lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;All people who are over 26 years old: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Select people who graduated with Bachelor&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?person ?degree&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person ex:degree ?degree .&lt;br /&gt;
        ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(&amp;quot;People who graduated with Bachelor: &amp;quot;+result[&amp;quot;person&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Delete cades photography interest&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE DATA {&lt;br /&gt;
        ex:Cade ex:interest ex:Photography .&lt;br /&gt;
        } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Print out Cades interests again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Check university names&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#Delete and insert university of valencia&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
    INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
    WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
        &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
# Check university names again&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT ?s ?o2&lt;br /&gt;
    WHERE  { &lt;br /&gt;
        ?s ex:degree ?o .&lt;br /&gt;
        ?o ex:degreeSource ?o2 .&lt;br /&gt;
      	}&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;o2&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
#Insert Sergio&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
    INSERT DATA {&lt;br /&gt;
        ex:Sergio a foaf:Person ;&lt;br /&gt;
        ex:address [ a ex:Address ;&lt;br /&gt;
                ex:city ex:Valenciay ;&lt;br /&gt;
                ex:country ex:Spain ;&lt;br /&gt;
                ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:state ex:California ;&lt;br /&gt;
                ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
        ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
                ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
                ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
                ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
        ex:expertise ex:Big_data,&lt;br /&gt;
            ex:Semantic_technologies,&lt;br /&gt;
            ex:Machine_learning;&lt;br /&gt;
        foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
sparql.setMethod(GET)&lt;br /&gt;
&lt;br /&gt;
# Describe Sergio&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    DESCRIBE ex:Sergio ?o&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ex:Sergio ?p ?o .&lt;br /&gt;
        ?o ?p2 ?o2 .&lt;br /&gt;
    }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
# Construct that any city is in the country in an address&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; &lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
    Where {&lt;br /&gt;
        ?s rdf:type ex:Address .&lt;br /&gt;
        ?s ex:city ?city .&lt;br /&gt;
        ?s ex:country ?country.&lt;br /&gt;
        }&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
    g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
        &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1757</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1757"/>
		<updated>2022-03-10T13:10:24Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFlib==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1756</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1756"/>
		<updated>2022-03-10T13:06:53Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
#hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
#for i in hobbies:&lt;br /&gt;
#    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1755</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1755"/>
		<updated>2022-03-10T13:05:50Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
 g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
 g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
 g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
 g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
 g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
 g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
 g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
 g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
 Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
 g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
 g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
 g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
 #hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
 #for i in hobbies:&lt;br /&gt;
 #    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1754</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1754"/>
		<updated>2022-03-10T13:05:11Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 from rdflib.collection import Collection&lt;br /&gt;
 from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
 from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
 DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
 DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
 g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
 g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
 g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
 g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
 g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
 g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
 g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
 g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
 Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
 g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
 g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
 g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
 #hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
 #for i in hobbies:&lt;br /&gt;
 #    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1753</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1753"/>
		<updated>2022-03-10T13:04:49Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
 from rdflib.collection import Collection&lt;br /&gt;
 from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
 from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
 DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
 DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
 g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
 g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
 g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
 g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
 g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
 g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
 g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
 g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
 Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
 g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
 g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
 g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
 #hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
 #for i in hobbies:&lt;br /&gt;
 #    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1752</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1752"/>
		<updated>2022-03-10T13:01:29Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 from rdflib.collection import Collection&lt;br /&gt;
 from rdflib import Graph, Namespace, Literal, URIRef&lt;br /&gt;
 from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 RL = Namespace(&#039;http://purl.org/vocab/relationship/&#039;)&lt;br /&gt;
 DBO = Namespace(&#039;https://dbpedia.org/ontology/&#039;)&lt;br /&gt;
 DBR = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
 g.namespace_manager.bind(&#039;exampleURI&#039;, EX)&lt;br /&gt;
 g.namespace_manager.bind(&#039;relationship&#039;, RL)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaOntology&#039;, DBO)&lt;br /&gt;
 g.namespace_manager.bind(&#039;dbpediaPage&#039;, DBR)&lt;br /&gt;
&lt;br /&gt;
 g.add((EX.Cade, RDF.type, FOAF.Person)) &lt;br /&gt;
 g.add((EX.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
 g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace&lt;br /&gt;
 g.add((DBR.France, DBO.capital, DBR.Paris)) &lt;br /&gt;
 g.add((EX.Cade, FOAF.age, Literal(27)))&lt;br /&gt;
 g.add((EX.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
 Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])&lt;br /&gt;
 g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.student))&lt;br /&gt;
 g.add((DBO.capital, EX.range, EX.city))&lt;br /&gt;
 g.add((EX.Mary, RDF.type, EX.kind))&lt;br /&gt;
 g.add((EX.Cade, RDF.type, EX.kindPerson))&lt;br /&gt;
&lt;br /&gt;
 #hobbies = [&#039;hiking&#039;, &#039;choclate&#039;, &#039;biology&#039;]&lt;br /&gt;
 #for i in hobbies:&lt;br /&gt;
 #    g.add((EX.Mary, FOAF.interest, EX[i]))&lt;br /&gt;
&lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
 import requests&lt;br /&gt;
 from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE&lt;br /&gt;
&lt;br /&gt;
 r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&lt;br /&gt;
 g = Graph()&lt;br /&gt;
 EX = Namespace(&#039;http://EXample.org/&#039;)&lt;br /&gt;
 g.bind(&amp;quot;ex&amp;quot;, EX)&lt;br /&gt;
&lt;br /&gt;
 for item in r[&#039;people&#039;]:&lt;br /&gt;
     craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
     g.add((EX[person], EX.onCraft, EX[craft]))&lt;br /&gt;
     g.add((EX[person], RDF.type, FOAF.Person))&lt;br /&gt;
     g.add((EX[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
     g.add((EX[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
 res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
     CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
     WHERE {&lt;br /&gt;
         ?person1 ex:onCraft ?craft .&lt;br /&gt;
         ?person2 ex:onCraft ?craft .&lt;br /&gt;
         }&lt;br /&gt;
 &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
 for triplet in res:&lt;br /&gt;
     if (triplet[0] != triplet[2]):&lt;br /&gt;
         g.add((triplet))&lt;br /&gt;
         &lt;br /&gt;
 print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1749</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1749"/>
		<updated>2022-03-10T12:46:09Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python&#039;s RDFlib. We will introduce other relevant libraries later.&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - Blazegraph==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==SPARQL - RDFlib==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Web APIs and JSON-LD==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==Semantic lifting - CSV==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
==RDFS==&lt;br /&gt;
===Solution 1===&lt;br /&gt;
somethingsomethin&lt;br /&gt;
&lt;br /&gt;
==Getting started==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Printing the triples of the Graph in a readable way===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The turtle format has the purpose of being more readable for humans. &lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Coding Tasks Lab 1===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.married, ex.Mary))&lt;br /&gt;
g.add((ex.France, ex.capital, ex.Paris))&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(&amp;quot;27&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.age, Literal(&amp;quot;26&amp;quot;, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Hiking))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, ex.interest, ex.Biology))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.Paris, ex.locatedIn, ex.France))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.Kind))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Mary, FOAF.name, Literal(&amp;quot;Mary&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, FOAF.Person))&lt;br /&gt;
g.add((ex.Mary, RDF.type, ex.Student))&lt;br /&gt;
g.add((ex.Cade, ex.Married, ex.Mary))&lt;br /&gt;
g.add((ex.Cade, FOAF.age, Literal(&#039;27&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Mary, FOAF.age, Literal(&#039;26&#039;, datatype=XSD.int)))&lt;br /&gt;
g.add((ex.Paris, RDF.type, ex.City))&lt;br /&gt;
g.add((ex.France, ex.Capital, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.hiking))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.Chocolate))&lt;br /&gt;
g.add((ex.Mary, FOAF.interest, ex.biology))&lt;br /&gt;
g.add((ex.France, ex.City, ex.Paris))&lt;br /&gt;
g.add((ex.Mary, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.Cade, ex.characteristic, ex.kind))&lt;br /&gt;
g.add((ex.France, RDF.type, ex.Country))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Basic RDF programming==&lt;br /&gt;
&lt;br /&gt;
===Different ways to create an address===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# How to represent the address of Cade Tracey. From probably the worst solution to the best.&lt;br /&gt;
&lt;br /&gt;
# Solution 1 -&lt;br /&gt;
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.livesIn, Literal(&amp;quot;1516_Henry_Street, Berkeley, California 94709, USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 2 - &lt;br /&gt;
# Seperate the different pieces information into their own triples&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, Literal(&amp;quot;Berkeley&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, Literal(&amp;quot;California&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, Literal(&amp;quot;USA&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.&lt;br /&gt;
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don&#039;t intend to say more about them. &lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_tracey, ex.street, Literal(&amp;quot;1516_Henry_Street&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.state, ex.California))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.zipcode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade_tracey, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 4 &lt;br /&gt;
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node. &lt;br /&gt;
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address. &lt;br /&gt;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID. &lt;br /&gt;
&lt;br /&gt;
# Address URI - CadeAdress&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, ex.Address))&lt;br /&gt;
g.add((ex.CadeAddress, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, ex.state, ex.California))&lt;br /&gt;
g.add((ex.CadeAddress, ex.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
# Blank node for Address.  &lt;br /&gt;
address = BNode()&lt;br /&gt;
g.add((ex.Cade_Tracey, ex.address, address))&lt;br /&gt;
g.add((address, RDF.type, ex.Address))&lt;br /&gt;
g.add((address, ex.street, Literal(&amp;quot;1516 Henry Street&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.city, ex.Berkeley))&lt;br /&gt;
g.add((address, ex.state, ex.California))&lt;br /&gt;
g.add((address, ex.postalCode, Literal(&amp;quot;94709&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((address, ex.country, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Solution 5 using existing vocabularies for address &lt;br /&gt;
&lt;br /&gt;
# (in this case https://schema.org/PostalAddress from schema.org). &lt;br /&gt;
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)&lt;br /&gt;
&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;https://dpbedia.org/resource/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))&lt;br /&gt;
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))&lt;br /&gt;
g.add((ex.CadeAddress, schema.streetAddress, Literal(&amp;quot;1516 Henry Street&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))&lt;br /&gt;
g.add((ex.CadeAddress, schema.postalCode, Literal(&amp;quot;94709&amp;quot;)))&lt;br /&gt;
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Typed Literals===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace&lt;br /&gt;
from rdflib.namespace import XSD&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))&lt;br /&gt;
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))&lt;br /&gt;
g.add((ex.Cade, FOAF.name, Literal(&amp;quot;Cade Tracey&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((ex.Cade, ex.birthday, Literal(&amp;quot;2006-01-01&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Writing and reading graphs/files===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
   # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.&lt;br /&gt;
g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a local file&lt;br /&gt;
parsed_graph = g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
   # Parsing a remote endpoint like Dbpedia&lt;br /&gt;
dbpedia_graph = g.parse(&amp;quot;http://dbpedia.org/resource/Pluto&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Graph Binding===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
#Graph Binding is useful for at least two reasons:&lt;br /&gt;
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.&lt;br /&gt;
#(2) When serializing the graph, the serialization will show the correct expected prefix &lt;br /&gt;
# instead of default namespace names ns1, ns2 etc.&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbp = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
schema = Namespace(&amp;quot;https://schema.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, dbp)&lt;br /&gt;
g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Collection Example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Sometimes we want to add many objects or subjects for the same predicate at once. &lt;br /&gt;
# In these cases we can use Collection() to save some time.&lt;br /&gt;
# In this case I want to add all countries that Emma has visited at once.&lt;br /&gt;
&lt;br /&gt;
b = BNode()&lt;br /&gt;
g.add((ex.Emma, ex.visit, b))&lt;br /&gt;
Collection(g, b,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
# OR&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Emma, ex.visit, ex.EmmaVisits))&lt;br /&gt;
Collection(g, ex.EmmaVisits,&lt;br /&gt;
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL==&lt;br /&gt;
&lt;br /&gt;
Also see the [[SPARQL Examples]] page!&lt;br /&gt;
&lt;br /&gt;
===Querying a local (&amp;quot;in memory&amp;quot;) graph===&lt;br /&gt;
&lt;br /&gt;
Example contents of the file family.ttl:&lt;br /&gt;
 @prefix rex: &amp;lt;http://example.org/royal#&amp;gt; .&lt;br /&gt;
 @prefix fam: &amp;lt;http://example.org/family#&amp;gt; .&lt;br /&gt;
 &lt;br /&gt;
 rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:SverreMagnus fam:hasParent rex:HaakonMagnus .&lt;br /&gt;
 rex:HaakonMagnus fam:hasParent rex:Harald .&lt;br /&gt;
 rex:MarthaLouise fam:hasParent rex:Harald .&lt;br /&gt;
 rex:HaakonMagnus fam:hasSister rex:MarthaLouise .&lt;br /&gt;
&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 qres = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
 PREFIX fam: &amp;lt;http://example.org/family#&amp;gt;&lt;br /&gt;
     SELECT ?child ?sister WHERE {&lt;br /&gt;
         ?child fam:hasParent ?parent .	&lt;br /&gt;
         ?parent fam:hasSister ?sister .&lt;br /&gt;
     }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
 for row in qres:&lt;br /&gt;
     print(&amp;quot;%s has aunt %s&amp;quot; % row)&lt;br /&gt;
&lt;br /&gt;
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:&lt;br /&gt;
 import rdflib&lt;br /&gt;
 &lt;br /&gt;
 g = rdflib.Graph()&lt;br /&gt;
 g.parse(&amp;quot;family.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
 &lt;br /&gt;
 q = rdflib.plugins.sparql.prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;SELECT ?child ?sister WHERE {&lt;br /&gt;
                   ?child fam:hasParent ?parent .&lt;br /&gt;
                   ?parent fam:hasSister ?sister .&lt;br /&gt;
        }&amp;quot;&amp;quot;&amp;quot;,&lt;br /&gt;
        initNs = { &amp;quot;fam&amp;quot;: &amp;quot;http://example.org/family#&amp;quot;})&lt;br /&gt;
 &lt;br /&gt;
 sm = rdflib.URIRef(&amp;quot;http://example.org/royal#SverreMagnus&amp;quot;)&lt;br /&gt;
 &lt;br /&gt;
 for row in g.query(q, initBindings={&#039;child&#039;: sm}):&lt;br /&gt;
         print(row)&lt;br /&gt;
&lt;br /&gt;
===Select all contents of lists (rdfllib.Collection)===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.&lt;br /&gt;
&lt;br /&gt;
PREFIX ex:   &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?visit&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Using parameters/variables in rdflib queries===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef&lt;br /&gt;
from rdflib.plugins.sparql import prepareQuery&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.Cade, ex.livesIn, ex.France))&lt;br /&gt;
g.add((ex.Anne, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.Sofie, ex.livesIn, ex.Sweden))&lt;br /&gt;
g.add((ex.Per, ex.livesIn, ex.Norway))&lt;br /&gt;
g.add((ex.John, ex.livesIn, ex.USA))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def find_people_from_country(country):&lt;br /&gt;
        country = URIRef(ex + country)&lt;br /&gt;
        q = prepareQuery(&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
         SELECT ?person WHERE { &lt;br /&gt;
         ?person ex:livesIn ?country.&lt;br /&gt;
         }&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
        capital_result = g.query(q, initBindings={&#039;country&#039;: country})&lt;br /&gt;
&lt;br /&gt;
        for row in capital_result:&lt;br /&gt;
            print(row)&lt;br /&gt;
&lt;br /&gt;
find_people_from_country(&amp;quot;Norway&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SELECTING data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph. &lt;br /&gt;
# You also need to add &amp;quot;sparql&amp;quot; to end of the URL like below.&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# SELECT all triples in the database.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;p&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# SELECT all interests of Cade&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT DISTINCT ?interest WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating data from Blazegraph via Python===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    INSERT DATA{&lt;br /&gt;
    ex:Cade ex:interest ex:Mathematics.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;https://query.wikidata.org/sparql&amp;quot;)&lt;br /&gt;
# In the query I want to select all the Vitamins in wikidata.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    SELECT ?nutrient ?nutrientLabel WHERE&lt;br /&gt;
{&lt;br /&gt;
  ?nutrient wdt:P279 wd:Q34956.&lt;br /&gt;
  SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;nutrient&amp;quot;][&amp;quot;value&amp;quot;], &amp;quot;   &amp;quot;, result[&amp;quot;nutrientLabel&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.&lt;br /&gt;
&lt;br /&gt;
===Download from BlazeGraph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
Dumps a database to a local RDF file.&lt;br /&gt;
You need to install the SPARQLWrapper package first...&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import datetime&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, RDFXML&lt;br /&gt;
&lt;br /&gt;
# your namespace, the default is &#039;kb&#039;&lt;br /&gt;
ns = &#039;kb&#039;&lt;br /&gt;
&lt;br /&gt;
# the SPARQL endpoint&lt;br /&gt;
endpoint = &#039;http://info216.i2s.uib.no/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# - the endpoint just moved, the old one was:&lt;br /&gt;
# endpoint = &#039;http://i2s.uib.no:8888/bigdata/namespace/&#039; + ns + &#039;/sparql&#039;&lt;br /&gt;
&lt;br /&gt;
# create wrapper&lt;br /&gt;
wrapper = SPARQLWrapper(endpoint)&lt;br /&gt;
&lt;br /&gt;
# prepare the SPARQL update&lt;br /&gt;
wrapper.setQuery(&#039;CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }&#039;)&lt;br /&gt;
wrapper.setReturnFormat(RDFXML)&lt;br /&gt;
&lt;br /&gt;
# execute the SPARQL update and convert the result to an rdflib.Graph &lt;br /&gt;
graph = wrapper.query().convert()&lt;br /&gt;
&lt;br /&gt;
# the destination file, with code to make it timestamped&lt;br /&gt;
destfile = &#039;rdf_dumps/slr-kg4news-&#039; + datetime.datetime.now().strftime(&#039;%Y%m%d-%H%M&#039;) + &#039;.rdf&#039;&lt;br /&gt;
&lt;br /&gt;
# serialize the result to file&lt;br /&gt;
graph.serialize(destination=destfile, format=&#039;ttl&#039;)&lt;br /&gt;
&lt;br /&gt;
# report and quit&lt;br /&gt;
print(&#039;Wrote %u triples to file %s .&#039; %&lt;br /&gt;
      (len(res), destfile))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Query Dbpedia with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://dbpedia.org/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt;&lt;br /&gt;
    PREFIX dbo: &amp;lt;http://dbpedia.org/ontology/&amp;gt;&lt;br /&gt;
    PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
    SELECT ?comment&lt;br /&gt;
    WHERE {&lt;br /&gt;
    dbr:Barack_Obama rdfs:comment ?comment.&lt;br /&gt;
    FILTER (langMatches(lang(?comment),&amp;quot;en&amp;quot;))&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;comment&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting CSV to RDF==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, RDFS, OWL&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# Load the CSV data as a pandas Dataframe.&lt;br /&gt;
csv_data = pd.read_csv(&amp;quot;task1.csv&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
csv_data = csv_data.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
&lt;br /&gt;
# Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
csv_data = csv_data.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in csv_data.iterrows():&lt;br /&gt;
    # The names of the people act as subjects.&lt;br /&gt;
    subject = row[&#039;Name&#039;]&lt;br /&gt;
    # Create triples: e.g. &amp;quot;Cade_Tracey - age - 27&amp;quot;&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;age&amp;quot;), Literal(row[&amp;quot;Age&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;married&amp;quot;), URIRef(ex + row[&amp;quot;Spouse&amp;quot;])))&lt;br /&gt;
    g.add((URIRef(ex + subject), URIRef(ex + &amp;quot;country&amp;quot;), URIRef(ex + row[&amp;quot;Country&amp;quot;])))&lt;br /&gt;
&lt;br /&gt;
    # If We want can add additional RDF/RDFS/OWL information e.g&lt;br /&gt;
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))&lt;br /&gt;
&lt;br /&gt;
# I remove triples that I marked as unknown earlier.&lt;br /&gt;
g.remove((None, None, URIRef(&amp;quot;http://example.org/unknown&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Clean printing of the graph.&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===CSV file for above example===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;quot;Name&amp;quot;,&amp;quot;Age&amp;quot;,&amp;quot;Spouse&amp;quot;,&amp;quot;Country&amp;quot;&lt;br /&gt;
&amp;quot;Cade Tracey&amp;quot;,&amp;quot;26&amp;quot;,&amp;quot;Mary Jackson&amp;quot;,&amp;quot;US&amp;quot;&lt;br /&gt;
&amp;quot;Bob Johnson&amp;quot;,&amp;quot;21&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;Canada&amp;quot;&lt;br /&gt;
&amp;quot;Mary Jackson&amp;quot;,&amp;quot;25&amp;quot;,&amp;quot;&amp;quot;,&amp;quot;France&amp;quot;&lt;br /&gt;
&amp;quot;Phil Philips&amp;quot;,&amp;quot;32&amp;quot;,&amp;quot;Catherine Smith&amp;quot;,&amp;quot;Japan&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Coding Tasks Lab 6=&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import pandas as pd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, XSD&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Removing unwanted characters&lt;br /&gt;
df = pd.read_csv(&#039;russia-investigation.csv&#039;)&lt;br /&gt;
# Here I deal with spaces (&amp;quot; &amp;quot;) in the data. I replace them with &amp;quot;_&amp;quot; so that URI&#039;s become valid.&lt;br /&gt;
df = df.replace(to_replace=&amp;quot; &amp;quot;, value=&amp;quot;_&amp;quot;, regex=True)&lt;br /&gt;
# This may seem odd, but in the data set we have a name like this:(&amp;quot;Scooter&amp;quot;). So we have to remove quotation marks&lt;br /&gt;
df = df.replace(to_replace=f&#039;&amp;quot;&#039;, value=&amp;quot;&amp;quot;, regex=True)&lt;br /&gt;
# # Here I mark all missing/empty data as &amp;quot;unknown&amp;quot;. This makes it easy to delete triples containing this later.&lt;br /&gt;
df = df.fillna(&amp;quot;unknown&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Loop through the CSV data, and then make RDF triples.&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
    name = row[&#039;investigation&#039;]&lt;br /&gt;
    investigation = URIRef(ex + name)&lt;br /&gt;
    g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
    investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasBeginTimeStamp, Literal(&lt;br /&gt;
        investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-end&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasEndTimeStamp, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.datetime)))&lt;br /&gt;
    investigation_end = row[&amp;quot;investigation-days&amp;quot;]&lt;br /&gt;
    g.add((investigation, sem.hasXSDDuration, Literal(&lt;br /&gt;
        investigation_end, datatype=XSD.Days)))&lt;br /&gt;
    person = row[&amp;quot;name&amp;quot;]&lt;br /&gt;
    person = URIRef(ex + person)&lt;br /&gt;
    g.add((investigation, sem.Actor, person))&lt;br /&gt;
    result = row[&#039;type&#039;]&lt;br /&gt;
    g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))&lt;br /&gt;
    overturned = row[&amp;quot;overturned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))&lt;br /&gt;
    pardoned = row[&amp;quot;pardoned&amp;quot;]&lt;br /&gt;
    g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Lifting XML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, URIRef&lt;br /&gt;
from rdflib.namespace import RDF, XSD, RDFS&lt;br /&gt;
import xml.etree.ElementTree as ET&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/TV/&amp;quot;)&lt;br /&gt;
prov = Namespace(&amp;quot;http://www.w3.org/ns/prov#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;prov&amp;quot;, prov)&lt;br /&gt;
&lt;br /&gt;
tree = ET.parse(&amp;quot;tv_shows.xml&amp;quot;)&lt;br /&gt;
root = tree.getroot()&lt;br /&gt;
&lt;br /&gt;
for tv_show in root.findall(&#039;tv_show&#039;):&lt;br /&gt;
    show_id = tv_show.attrib[&amp;quot;id&amp;quot;]&lt;br /&gt;
    title = tv_show.find(&amp;quot;title&amp;quot;).text&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))&lt;br /&gt;
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
    for actor in tv_show.findall(&amp;quot;actor&amp;quot;):&lt;br /&gt;
        first_name = actor.find(&amp;quot;firstname&amp;quot;).text&lt;br /&gt;
        last_name = actor.find(&amp;quot;lastname&amp;quot;).text&lt;br /&gt;
        full_name = first_name + &amp;quot;_&amp;quot; + last_name&lt;br /&gt;
        &lt;br /&gt;
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))&lt;br /&gt;
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==RDFS==&lt;br /&gt;
&lt;br /&gt;
===RDFS-plus (OWL) Properties===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.married, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.ReflexiveProperty))&lt;br /&gt;
g.add((ex.livesWith, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.TransitiveProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.sibling, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasFather, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.fatherOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
# Sometimes there is no definite answer, and it comes down to how we want to model our properties&lt;br /&gt;
# e.g is livesWith a transitive property? Usually yes, but we can also want to specify that a child lives with both of her divorced parents.&lt;br /&gt;
# which means that: (mother livesWith child % child livesWith father) != mother livesWith father. Which makes it non-transitive.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===RDFS inference with RDFLib===&lt;br /&gt;
You can use the OWL-RL package to add inference capabilities to RDFLib. It can be installed using the pip install command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install owlrl&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Or download it from [https://github.com/RDFLib/OWL-RL GitHub] and copy the &#039;&#039;owlrl&#039;&#039; subfolder into your project folder next to your Python files.&lt;br /&gt;
&lt;br /&gt;
[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]&lt;br /&gt;
&lt;br /&gt;
Example program to get you started. In this example we are creating the graph using sparql.update, but it is also possible to parse the data from a file.&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib.plugins.sparql.update&lt;br /&gt;
import owlrl.RDFSClosure&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
ex = rdflib.Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
g.bind(&#039;&#039;, ex)&lt;br /&gt;
&lt;br /&gt;
g.update(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates rdf:type ex:Man .&lt;br /&gt;
    ex:Man rdfs:subClassOf ex:Mortal .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
# RDF_Semantics parameters:	&lt;br /&gt;
# - graph (rdflib.Graph) – The RDF graph to be extended.&lt;br /&gt;
# - axioms (bool) – Whether (non-datatype) axiomatic triples should be added or not.&lt;br /&gt;
# - daxioms (bool) – Whether datatype axiomatic triples should be added or not.&lt;br /&gt;
# - rdfs (bool) – Whether RDFS inference is also done (used in subclassed only).&lt;br /&gt;
# For now, you will in most cases use all False in RDFS_Semtantics.&lt;br /&gt;
&lt;br /&gt;
# Generates the closure of the graph - generates the new entailed triples, but does not add them to the graph.&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
# Adds the new triples to the graph and empties the RDFS triple-container.&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Ask-query to check whether a new triple has been generated from the entailment.&lt;br /&gt;
b = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:Socrates rdf:type ex:Mortal .&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(&#039;Result: &#039; + bool(b))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Language tagged RDFS labels=== &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal&lt;br /&gt;
from rdflib.namespace import RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Frankrike&amp;quot;, lang=&amp;quot;no&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;France&amp;quot;, lang=&amp;quot;en&amp;quot;)))&lt;br /&gt;
g.add((ex.France, RDFS.label, Literal(&amp;quot;Francia&amp;quot;, lang=&amp;quot;es&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL== &lt;br /&gt;
===Basic inference with RDFLib=== &lt;br /&gt;
&lt;br /&gt;
You can use the OWL-RL package again as for Lecture 5.&lt;br /&gt;
&lt;br /&gt;
Instead of: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
you can write this to get both RDFS and basic RDFS Plus / OWL inference:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# The next three lines add inferred triples to g.&lt;br /&gt;
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl.closure()&lt;br /&gt;
owl.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example updates and queries:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:Socrates ex:hasWife ex:Xanthippe .&lt;br /&gt;
    ex:hasHusband owl:inverseOf ex:hasWife .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Xanthippe ex:hasHusband ex:Socrates .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasHusband ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .&lt;br /&gt;
    ex:hasSpouse rdf:type owl:SymmetricProperty . &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
   ex:Socrates ^ex:hasSpouse ex:Xanthippe .&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===XML Data for above example===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;data&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1050&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;The_Sopranos&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;James&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Gandolfini&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
    &amp;lt;tv_show id=&amp;quot;1066&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;title&amp;gt;Seinfeld&amp;lt;/title&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jerry&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Seinfeld&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Julia&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Louis-dreyfus&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
        &amp;lt;actor&amp;gt;&lt;br /&gt;
            &amp;lt;firstname&amp;gt;Jason&amp;lt;/firstname&amp;gt;&lt;br /&gt;
            &amp;lt;lastname&amp;gt;Alexander&amp;lt;/lastname&amp;gt;&lt;br /&gt;
        &amp;lt;/actor&amp;gt;&lt;br /&gt;
    &amp;lt;/tv_show&amp;gt;&lt;br /&gt;
&amp;lt;/data&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lifting HTML to RDF==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from bs4 import BeautifulSoup as bs, NavigableString&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace&lt;br /&gt;
from rdflib.namespace import RDF&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
html = open(&amp;quot;tv_shows.html&amp;quot;).read()&lt;br /&gt;
html = bs(html, features=&amp;quot;html.parser&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
shows = html.find_all(&#039;li&#039;, attrs={&#039;class&#039;: &#039;show&#039;})&lt;br /&gt;
for show in shows:&lt;br /&gt;
    title = show.find(&amp;quot;h3&amp;quot;).text&lt;br /&gt;
    actors = show.find(&#039;ul&#039;, attrs={&#039;class&#039;: &#039;actor_list&#039;})&lt;br /&gt;
    for actor in actors:&lt;br /&gt;
        if isinstance(actor, NavigableString):&lt;br /&gt;
            continue&lt;br /&gt;
        else:&lt;br /&gt;
            actor = actor.text.replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;)&lt;br /&gt;
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))&lt;br /&gt;
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))&lt;br /&gt;
&lt;br /&gt;
    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===HTML code for the example above===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;div class=&amp;quot;tv_shows&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;ul&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;The_Sopranos&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;James Gandolfini&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;lt;li class=&amp;quot;show&amp;quot;&amp;gt;&lt;br /&gt;
                &amp;lt;h3&amp;gt;Seinfeld&amp;lt;/h3&amp;gt;&lt;br /&gt;
                &amp;lt;div class=&amp;quot;irrelevant_data&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
                &amp;lt;ul class=&amp;quot;actor_list&amp;quot;&amp;gt;&lt;br /&gt;
                    &amp;lt;li &amp;gt;Jerry Seinfeld&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Jason Alexander&amp;lt;/li&amp;gt;&lt;br /&gt;
                    &amp;lt;li&amp;gt;Julia Louis-Dreyfus&amp;lt;/li&amp;gt;&lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;br /&gt;
            &amp;lt;/li&amp;gt;&lt;br /&gt;
        &amp;lt;/ul&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Web APIs with JSON==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
import json&lt;br /&gt;
import pprint&lt;br /&gt;
&lt;br /&gt;
# Retrieve JSON data from API service URL. Then load it with the json library as a json object.&lt;br /&gt;
url = &amp;quot;http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;#country=ES&amp;amp;username=demo&amp;quot;&lt;br /&gt;
data = requests.get(url).content.decode(&amp;quot;utf-8&amp;quot;)&lt;br /&gt;
data = json.loads(data)&lt;br /&gt;
pprint.pprint(data)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==JSON-LD==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
&lt;br /&gt;
example = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;name&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/name&amp;quot;,&lt;br /&gt;
    &amp;quot;homepage&amp;quot;: {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/homepage&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;@id&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@id&amp;quot;: &amp;quot;http://me.markus-lanthaler.com/&amp;quot;,&lt;br /&gt;
  &amp;quot;name&amp;quot;: &amp;quot;Markus Lanthaler&amp;quot;,&lt;br /&gt;
  &amp;quot;homepage&amp;quot;: &amp;quot;http://www.markus-lanthaler.com/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# json-ld parsing automatically deals with @contexts&lt;br /&gt;
g.parse(data=example, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# serialisation does expansion by default&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&lt;br /&gt;
# by supplying a context object, serialisation can do compaction&lt;br /&gt;
context = {&lt;br /&gt;
    &amp;quot;foaf&amp;quot;: &amp;quot;http://xmlns.com/foaf/0.1/&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
for line in g.serialize(format=&#039;json-ld&#039;, context=context).decode().splitlines():&lt;br /&gt;
    print(line)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].&#039;&#039; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==OWL - Complex Classes and Restrictions==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, Literal, Namespace, BNode&lt;br /&gt;
from rdflib.namespace import RDF, OWL, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;owl&amp;quot;, OWL)&lt;br /&gt;
&lt;br /&gt;
# a Season is either Autumn, Winter, Spring, Summer&lt;br /&gt;
seasons = BNode()&lt;br /&gt;
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])&lt;br /&gt;
g.add((ex.Season, OWL.oneOf, seasons))&lt;br /&gt;
&lt;br /&gt;
# A Parent is a Father or Mother&lt;br /&gt;
b = BNode()&lt;br /&gt;
Collection(g, b, [ex.Father, ex.Mother])&lt;br /&gt;
g.add((ex.Parent, OWL.unionOf, b))&lt;br /&gt;
&lt;br /&gt;
# A Woman is a person who has the &amp;quot;female&amp;quot; gender&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.gender))&lt;br /&gt;
g.add((br, OWL.hasValue, ex.Female))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Woman, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who only eats vegetarian food&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.allValuesFrom, ex.VeganFood))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A vegetarian is a Person who can not eat meat.&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.eats))&lt;br /&gt;
g.add((br, OWL.QualifiedCardinality, Literal(0)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Meat))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Vegetarian, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# A Worried Parent is a parent who has at least one sick child&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.hasChild))&lt;br /&gt;
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))&lt;br /&gt;
g.add((br, OWL.onClass, ex.Sick))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Parent, br])&lt;br /&gt;
g.add((ex.WorriedParent, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# using the restriction above, If we now write...: &lt;br /&gt;
g.add((ex.Bob, RDF.type, ex.Parent))&lt;br /&gt;
g.add((ex.Bob, ex.hasChild, ex.John))&lt;br /&gt;
g.add((ex.John, RDF.type, ex.Sick))&lt;br /&gt;
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn&#039;t specify it ourselves because Bob fullfills the restriction and Parent requirements.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Protege-OWL reasoning with HermiT==&lt;br /&gt;
&lt;br /&gt;
[[:File:DL-reasoning-RoyalFamily-final.owl.txt | Example file]] from Lecture 13 about OWL-DL, rules and reasoning.&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1733</id>
		<title>Lab: Semantic Lifting - CSV</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1733"/>
		<updated>2022-03-01T14:16:56Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Lab 6: Semantic Lifting - CSV =&lt;br /&gt;
&lt;br /&gt;
== Topic ==&lt;br /&gt;
Today&#039;s topic involves lifting data in CSV format into RDF. The goal is for you to learn how we can convert non-semantic data into RDF as well as getting familiar with some common vocabularies.&lt;br /&gt;
&lt;br /&gt;
Fortunately, CSV is already structured in a way that makes the creation of triples relatively easy.&lt;br /&gt;
&lt;br /&gt;
We will also use Pandas Dataframes which will contain our CSV data in python code, and we&#039;ll do some basic data manipulation to improve our output data.&lt;br /&gt;
&lt;br /&gt;
== Relevant Libraries - Classes, Functions and Methods and Vocabularies==&lt;br /&gt;
=== Libraries ===&lt;br /&gt;
* RDFlib concepts from earlier (Graph, Namespace, URIRef, Literal, BNode)&lt;br /&gt;
* Pandas: DataFrame, apply, iterrows, astype&lt;br /&gt;
* DBpedia Spotlight&lt;br /&gt;
&lt;br /&gt;
=== Semantic Vocabularies ===&lt;br /&gt;
You do not have to use the same ones, but these should be well suited.&lt;br /&gt;
* RDF: type&lt;br /&gt;
* RDFS: label&lt;br /&gt;
* Simple Event Ontology (sem): Event, eventType, Actor, hasActor, hasActorType, hasBeginTimeStamp, EndTimeStamp, hasTime, hasSubEvent&lt;br /&gt;
* TimeLine Ontology (tl): durationInt&lt;br /&gt;
* An example-namespace to represent terms not found elsewhere (ex): IndictmentDays, Overturned, Pardoned&lt;br /&gt;
* DBpedia&lt;br /&gt;
&lt;br /&gt;
== Tasks ==&lt;br /&gt;
Today we will be working with FiveThirtyEight&#039;s russia-investigation dataset. It contains special investigations conducted by the United States since the Watergate-investigation with information about them to May 2017. If you found the last weeks exercice doable, I recommend trying to write this with object-oriented programming (OOP) structure, as this tends to make for cleaner code.&lt;br /&gt;
&lt;br /&gt;
It contains the following columns:&lt;br /&gt;
* investigation&lt;br /&gt;
* investigation-start&lt;br /&gt;
* investigation-end&lt;br /&gt;
* investigation-days&lt;br /&gt;
* name&lt;br /&gt;
* indictment-days&lt;br /&gt;
* type&lt;br /&gt;
* cp-date&lt;br /&gt;
* cp-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardoned&lt;br /&gt;
* american&lt;br /&gt;
* president&lt;br /&gt;
&lt;br /&gt;
More information about the columns and the dataset here: https://github.com/fivethirtyeight/data/tree/master/russia-investigation&lt;br /&gt;
&lt;br /&gt;
Our goal is to convert this non-semantic dataset into a semantic one. To do this we will go row-by-row through the dataset and extract the content of each column.&lt;br /&gt;
An investigation may have multiple rows in the dataset if it investigates multiple people, you can choose to represent these as one or multiple entities in the graph. Each investigation may also have a sub-event representing the result of the investigation, this could for instance be indictment or guilty-plea.&lt;br /&gt;
&lt;br /&gt;
For a row we will start by creating a resource representing the investigation. In this example we handle all investigations with the same name as the samme entity, and will therefore use the name of the investigation (&amp;quot;investigation&amp;quot;-column) to create the URI:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
name = row[&amp;quot;investigation&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
investigation = URIRef(ex + name)&lt;br /&gt;
g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further we will create a relation between the investigation and all its associated columns. For when the investigation started we&#039;ll use the &amp;quot;investigation-start&amp;quot;-column and we can use the property sem:hasBeginTimeStamp:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
g.add((investigation, sem.hasBeginTimeStamp, Literal(investigation_start, datatype=XSD.date)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To represent the result of the investigation, if it has one, We can create another entity and connect it to the investigation using the sem:hasSubEvent. If so the following columns can be attributed to the sub-event:&lt;br /&gt;
* type&lt;br /&gt;
* indictment-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardon&lt;br /&gt;
* cp_date&lt;br /&gt;
* cp_days&lt;br /&gt;
* name (the name of the investigatee, not the name of the investigation)&lt;br /&gt;
&lt;br /&gt;
=== Code to get you started ===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import pandas as pd&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;data/investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	# Do something here to add the content of the row to the graph &lt;br /&gt;
	pass&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== If you have more time ==&lt;br /&gt;
If you have not already you should include some checks to assure that you don&#039;t add any empty columns to your graph.&lt;br /&gt;
&lt;br /&gt;
If you have more time you can implement DBpedia Spotlight to link the people mentioned in the dataset to DBpedia resources.&lt;br /&gt;
You can use the same code example as in the last lab, but you will need some error-handling for when DBpedia is unable to find a match. For instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity, filters={&amp;quot;types&amp;quot;:&amp;quot;DBpedia:Person&amp;quot;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(SERVER, entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
		# Implement some error handling here&lt;br /&gt;
	return annotations&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here we use the types-filter with DBpedia:Person, as we only want it to match with people. You can choose to only implement the URIs in the response, or the types as well. An issue here is that &lt;br /&gt;
&lt;br /&gt;
== Useful readings ==&lt;br /&gt;
* [https://github.com/fivethirtyeight/data/tree/master/russia-investigation Information about the dataset]&lt;br /&gt;
* [https://towardsdatascience.com/pandas-dataframe-playing-with-csv-files-944225d19ff Article about working with pandas.DataFrames and CSV]&lt;br /&gt;
* [https://pandas.pydata.org/pandas-docs/stable/reference/frame.html Pandas DataFrame documentation]&lt;br /&gt;
* [https://semanticweb.cs.vu.nl/2009/11/sem/#sem:eventType Simple Event Ontology Descripiton]&lt;br /&gt;
* [http://motools.sourceforge.net/timeline/timeline.html The TimeLine Ontology Description]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1732</id>
		<title>Lab: Semantic Lifting - CSV</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1732"/>
		<updated>2022-03-01T09:58:02Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Lab 6: Semantic Lifting - CSV =&lt;br /&gt;
&lt;br /&gt;
== Topic ==&lt;br /&gt;
Today&#039;s topic involves lifting data in CSV format into RDF. The goal is for you to learn how we can convert non-semantic data into RDF as well as getting familiar with some common vocabularies.&lt;br /&gt;
&lt;br /&gt;
Fortunately, CSV is already structured in a way that makes the creation of triples relatively easy.&lt;br /&gt;
&lt;br /&gt;
We will also use Pandas Dataframes which will contain our CSV data in python code, and we&#039;ll do some basic data manipulation to improve our output data.&lt;br /&gt;
&lt;br /&gt;
== Relevant Libraries - Classes, Functions and Methods and Vocabularies==&lt;br /&gt;
=== Libraries ===&lt;br /&gt;
* RDFlib concepts from earlier (Graph, Namespace, URIRef, Literal, BNode)&lt;br /&gt;
* Pandas: DataFrame, apply, iterrows, astype&lt;br /&gt;
* DBpedia Spotlight&lt;br /&gt;
&lt;br /&gt;
=== Semantic Vocabularies ===&lt;br /&gt;
You do not have to use the same ones, but these should be well suited.&lt;br /&gt;
* RDF: type&lt;br /&gt;
* RDFS: label&lt;br /&gt;
* Simple Event Ontology (sem): Event, eventType, Actor, hasActor, hasActorType, hasBeginTimeStamp, EndTimeStamp, hasTime, hasSubEvent&lt;br /&gt;
* TimeLine Ontology (tl): durationInt&lt;br /&gt;
* An example-namespace to represent terms not found elsewhere (ex): IndictmentDays, Overturned, Pardoned&lt;br /&gt;
* DBpedia&lt;br /&gt;
&lt;br /&gt;
== Tasks ==&lt;br /&gt;
Today we will be working with FiveThirtyEight&#039;s russia-investigation dataset. It contains special investigations conducted by the United States since the Watergate-investigation with information about them to May 2017. If you found the last weeks exercice doable, I recommend trying to write this with object-oriented programming (OOP) structure, as this tends to make for cleaner code.&lt;br /&gt;
&lt;br /&gt;
It contains the following columns:&lt;br /&gt;
* investigation&lt;br /&gt;
* investigation-start&lt;br /&gt;
* investigation-end&lt;br /&gt;
* investigation-days&lt;br /&gt;
* name&lt;br /&gt;
* indictment-days&lt;br /&gt;
* type&lt;br /&gt;
* cp-date&lt;br /&gt;
* cp-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardoned&lt;br /&gt;
* american&lt;br /&gt;
* president&lt;br /&gt;
&lt;br /&gt;
More information about the columns and the dataset here: https://github.com/fivethirtyeight/data/tree/master/russia-investigation&lt;br /&gt;
&lt;br /&gt;
Our goal is to convert this non-semantic dataset into a semantic one. To do this we will go row-by-row through the dataset and extract the content of each column.&lt;br /&gt;
An investigation may have multiple rows in the dataset if it investigates multiple people, you can choose to represent these as one or multiple entities in the graph. Each investigation may also have a sub-event representing the result of the investigation, this could for instance be indictment or guilty-plea.&lt;br /&gt;
&lt;br /&gt;
For a row we will start by creating a resource representing the investigation. In this example we handle all investigations with the same name as the samme entity, and will therefore use the name of the investigation (&amp;quot;investigation&amp;quot;-column) to create the URI:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
name = row[&amp;quot;investigation&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
investigation = URIRef(ex + name)&lt;br /&gt;
g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further we will create a relation between the investigation and all its associated columns. For when the investigation started we&#039;ll use the &amp;quot;investigation-start&amp;quot;-column and we can use the property sem:hasBeginTimeStamp:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
g.add((investigation, sem.hasBeginTimeStamp, Literal(investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To represent the result of the investigation, if it has one, We can create another entity and connect it to the investigation using the sem:hasSubEvent. If so the following columns can be attributed to the sub-event:&lt;br /&gt;
* type&lt;br /&gt;
* indictment-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardon&lt;br /&gt;
* cp_date&lt;br /&gt;
* cp_days&lt;br /&gt;
* name (the name of the investigatee, not the name of the investigation)&lt;br /&gt;
&lt;br /&gt;
=== Code to get you started ===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import pandas as pd&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;data/investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for index, row in df.iterrows():&lt;br /&gt;
	# Do something here to add the content of the row to the graph &lt;br /&gt;
	pass&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== If you have more time ==&lt;br /&gt;
If you have not already you should include some checks to assure that you don&#039;t add any empty columns to your graph.&lt;br /&gt;
&lt;br /&gt;
If you have more time you can implement DBpedia Spotlight to link the people mentioned in the dataset to DBpedia resources.&lt;br /&gt;
You can use the same code example as in the last lab, but you will need some error-handling for when DBpedia is unable to find a match. For instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity, filters={&amp;quot;types&amp;quot;:&amp;quot;DBpedia:Person&amp;quot;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(SERVER, entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
		# Implement some error handling here&lt;br /&gt;
	return annotations&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here we use the types-filter with DBpedia:Person, as we only want it to match with people. You can choose to only implement the URIs in the response, or the types as well. An issue here is that &lt;br /&gt;
&lt;br /&gt;
== Useful readings ==&lt;br /&gt;
* [https://github.com/fivethirtyeight/data/tree/master/russia-investigation Information about the dataset]&lt;br /&gt;
* [https://towardsdatascience.com/pandas-dataframe-playing-with-csv-files-944225d19ff Article about working with pandas.DataFrames and CSV]&lt;br /&gt;
* [https://pandas.pydata.org/pandas-docs/stable/reference/frame.html Pandas DataFrame documentation]&lt;br /&gt;
* [https://semanticweb.cs.vu.nl/2009/11/sem/#sem:eventType Simple Event Ontology Descripiton]&lt;br /&gt;
* [http://motools.sourceforge.net/timeline/timeline.html The TimeLine Ontology Description]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_RDFS&amp;diff=1727</id>
		<title>Lab: RDFS</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_RDFS&amp;diff=1727"/>
		<updated>2022-02-24T12:19:23Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 7: RDFS Programming with rdflib and owlrl=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Basic RDFS graph programming in RDFlib.&lt;br /&gt;
Entailments and axioms with owlrl.&lt;br /&gt;
&lt;br /&gt;
==Classes/Methods/Vocabularies==&lt;br /&gt;
owlrl.RDFSClosure (RDFS_Semantics, closure, flush_stored_triples)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Vocabularies: &#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
RDF.type&lt;br /&gt;
&lt;br /&gt;
RDFS.subClassOf, RDFS.subPropertyOf, RDFS.domain, RDFS.range, RDFS.label, RDFS.comment, &lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
First, pip install owlrl.&lt;br /&gt;
The RDFS Vocabulary can be imported from rdflib.namespace, just like FOAF or RDF.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Consider the following Scenario:&#039;&#039;&#039;&lt;br /&gt;
&amp;quot;University of California and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education institutions (HEIs). Only persons can have an expertise, and what they have expertise in is always a subject. Only persons can graduate from a HEI. If you are a student, you are in fact a person as well. That a person is married to someone, means that they know them. Finally, if a person has a name, that name is also the label of that entity.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Create RDFS triples corresponding to the text above with RDFlib&#039;&#039;&#039; - if you can, try to build on&lt;br /&gt;
your example from lab 2! &lt;br /&gt;
&lt;br /&gt;
To create the graph in python, you can just use the g.add syntax as we have done previously, or you can use the following code sample to parse a file into a graph:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Create the graph&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Parse input data into the graph, format is dependent on the file format. Here turtle (ttl). And location is the path to the local file&lt;br /&gt;
g.parse(location=&amp;quot;input.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using these three lines we can add automatically the inferred triples (like ex:University rdf:type ex:Higher_Education_Institute) :&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
rdfs.closure()&lt;br /&gt;
rdfs.flush_stored_triples()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After you have done this, try to add the following scenario to you graph as well:&lt;br /&gt;
&amp;quot;Having a degree from a HEI means that you have also graduated from that HEI. That a city is a capital of a country means that this city is located in that country. That someone was involved in a meeting, means that they have met the other participants. If someone partook in a meeting somewhere, means that they have visited that place&amp;quot;&lt;br /&gt;
To do this, you will have to swap out the line&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
with&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
As some of these triples require more advanced reasoning.&lt;br /&gt;
&lt;br /&gt;
Check that simple inference works -  make sure that your graph contains triples like these, even if&lt;br /&gt;
you have not asserted them explicitly:&lt;br /&gt;
* that University of California and Valencia are HEIs&lt;br /&gt;
* that Cade, Emma, and Mary are all persons&lt;br /&gt;
* that Cade and Emma have both graduated from some HEI&lt;br /&gt;
* that Cade knows Mary&lt;br /&gt;
&lt;br /&gt;
One way to check if the triples are there:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
universities = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
ASK {&lt;br /&gt;
    ex:University_of_California rdf:type ex:Higher_Education_Institution.&lt;br /&gt;
} &lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
print(bool(universities))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rewrite some of your existing code to use rdfs:label in a triple and add an rdfs:comment to the same resource.&lt;br /&gt;
&lt;br /&gt;
==If you have more time...==&lt;br /&gt;
Create a new RDFS graph that wraps an empty graph. This graph contains only RDFS axioms. Write it out in Turtle and check that you understand  the meaning and purpose of each axiom.&lt;br /&gt;
&lt;br /&gt;
Create an RDF (not RDFS) graph that contains all the triples in your first graph (the one with all the people and universities). Subtract all the triples in the axiom graph from the people/university graph. Write it out to see that you are left with only the asserted and entailed triples and that none of the axioms remain.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- Download the SKOS vocabulary from https://www.w3.org/2009/08/skos-reference/skos.rdf and save it to a file called, e.g., SKOS.rdf .&lt;br /&gt;
Use the schemagen tool (it is inside your Jena folders, for example under apache-jena-3.1.1/bin) to generate a Java class for the SKOS vocabulary. &lt;br /&gt;
You need to do this from a console window, using a command like &amp;quot;&amp;lt;path&amp;gt;/schemagen -i &amp;lt;infile.rdf&amp;gt; -o &amp;lt;outfile.java&amp;gt;&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Copy the SKOS.java file into your project in the same package as your other Java files,  and try to use SKOS properties &lt;br /&gt;
where they fit, for example to organise the keywords for interests and expertise.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Useful Readings==&lt;br /&gt;
*[https://wiki.uib.no/info216/index.php/File:S05-RDFS-11.pdf Lecture Notes]&lt;br /&gt;
*[https://wiki.uib.no/info216/index.php/Python_Examples Example page]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1726</id>
		<title>Lab: Semantic Lifting - CSV</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Semantic_Lifting_-_CSV&amp;diff=1726"/>
		<updated>2022-02-24T12:19:07Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Lab 6: Semantic Lifting - CSV =&lt;br /&gt;
&lt;br /&gt;
== Topic ==&lt;br /&gt;
Today&#039;s topic involves lifting data in CSV format into RDF. The goal is for you to learn how we can convert non-semantic data into RDF as well as getting familiar with some common vocabularies.&lt;br /&gt;
&lt;br /&gt;
Fortunately, CSV is already structured in a way that makes the creation of triples relatively easy.&lt;br /&gt;
&lt;br /&gt;
We will also use Pandas Dataframes which will contain our CSV data in python code, and we&#039;ll do some basic data manipulation to improve our output data.&lt;br /&gt;
&lt;br /&gt;
== Relevant Libraries - Classes, Functions and Methods and Vocabularies==&lt;br /&gt;
=== Libraries ===&lt;br /&gt;
* RDFlib concepts from earlier (Graph, Namespace, URIRef, Literal, BNode)&lt;br /&gt;
* Pandas: DataFrame, apply, iterrows, astype&lt;br /&gt;
* DBpedia Spotlight&lt;br /&gt;
&lt;br /&gt;
=== Semantic Vocabularies ===&lt;br /&gt;
You do not have to use the same ones, but these should be well suited.&lt;br /&gt;
* RDF: type&lt;br /&gt;
* RDFS: label&lt;br /&gt;
* Simple Event Ontology (sem): Event, eventType, Actor, hasActor, hasActorType, hasBeginTimeStamp, EndTimeStamp, hasTime, hasSubEvent&lt;br /&gt;
* TimeLine Ontology (tl): durationInt&lt;br /&gt;
* An example-namespace to represent terms not found elsewhere (ex): IndictmentDays, Overturned, Pardoned&lt;br /&gt;
* DBpedia&lt;br /&gt;
&lt;br /&gt;
== Tasks ==&lt;br /&gt;
Today we will be working with FiveThirtyEight&#039;s russia-investigation dataset. It contains special investigations conducted by the United States since the Watergate-investigation with information about them to May 2017. If you found the last weeks exercice doable, I recommend trying to write this with object-oriented programming (OOP) structure, as this tends to make for cleaner code.&lt;br /&gt;
&lt;br /&gt;
It contains the following columns:&lt;br /&gt;
* investigation&lt;br /&gt;
* investigation-start&lt;br /&gt;
* investigation-end&lt;br /&gt;
* investigation-days&lt;br /&gt;
* name&lt;br /&gt;
* indictment-days&lt;br /&gt;
* type&lt;br /&gt;
* cp-date&lt;br /&gt;
* cp-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardoned&lt;br /&gt;
* american&lt;br /&gt;
* president&lt;br /&gt;
&lt;br /&gt;
More information about the columns and the dataset here: https://github.com/fivethirtyeight/data/tree/master/russia-investigation&lt;br /&gt;
&lt;br /&gt;
Our goal is to convert this non-semantic dataset into a semantic one. To do this we will go row-by-row through the dataset and extract the content of each column.&lt;br /&gt;
An investigation may have multiple rows in the dataset if it investigates multiple people, you can choose to represent these as one or multiple entities in the graph. Each investigation may also have a sub-event representing the result of the investigation, this could for instance be indictment or guilty-plea.&lt;br /&gt;
&lt;br /&gt;
For a row we will start by creating a resource representing the investigation. In this example we handle all investigations with the same name as the samme entity, and will therefore use the name of the investigation (&amp;quot;investigation&amp;quot;-column) to create the URI:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
name = row[&amp;quot;investigation&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
investigation = URIRef(ex + name)&lt;br /&gt;
g.add((investigation, RDF.type, sem.Event))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further we will create a relation between the investigation and all its associated columns. For when the investigation started we&#039;ll use the &amp;quot;investigation-start&amp;quot;-column and we can use the property sem:hasBeginTimeStamp:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
investigation_start = row[&amp;quot;investigation-start&amp;quot;]&lt;br /&gt;
&lt;br /&gt;
g.add((investigation, sem.hasBeginTimeStamp, Literal(investigation_start, datatype=XSD.datetime)))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To represent the result of the investigation, if it has one, We can create another entity and connect it to the investigation using the sem:hasSubEvent. If so the following columns can be attributed to the sub-event:&lt;br /&gt;
* type&lt;br /&gt;
* indictment-days&lt;br /&gt;
* overturned&lt;br /&gt;
* pardon&lt;br /&gt;
* cp_date&lt;br /&gt;
* cp_days&lt;br /&gt;
* name (the name of the investigatee, not the name of the investigation)&lt;br /&gt;
&lt;br /&gt;
=== Code to get you started ===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import pandas as pd&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, BNode&lt;br /&gt;
from rdflib.namespace import RDF, RDFS, XSD&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
dbr = Namespace(&amp;quot;http://dbpedia.org/resource/&amp;quot;)&lt;br /&gt;
sem = Namespace(&amp;quot;http://semanticweb.cs.vu.nl/2009/11/sem/&amp;quot;)&lt;br /&gt;
tl = Namespace(&amp;quot;http://purl.org/NET/c4dm/timeline.owl#&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbr&amp;quot;, dbr)&lt;br /&gt;
g.bind(&amp;quot;sem&amp;quot;, sem)&lt;br /&gt;
g.bind(&amp;quot;tl&amp;quot;, tl)&lt;br /&gt;
&lt;br /&gt;
df = pd.read_csv(&amp;quot;data/investigations.csv&amp;quot;)&lt;br /&gt;
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype(&amp;quot;str&amp;quot;) to convert the content of the columns to a string.&lt;br /&gt;
df[&amp;quot;name&amp;quot;] = df[&amp;quot;name&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
df[&amp;quot;type&amp;quot;] = df[&amp;quot;type&amp;quot;].astype(&amp;quot;str&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# iterrows creates an iterable object (list of rows)&lt;br /&gt;
for row in df.iterrows():&lt;br /&gt;
	# Do something here to add the content of the row to the graph &lt;br /&gt;
	pass&lt;br /&gt;
&lt;br /&gt;
g.serialize(&amp;quot;output.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== If you have more time ==&lt;br /&gt;
If you have not already you should include some checks to assure that you don&#039;t add any empty columns to your graph.&lt;br /&gt;
&lt;br /&gt;
If you have more time you can implement DBpedia Spotlight to link the people mentioned in the dataset to DBpedia resources.&lt;br /&gt;
You can use the same code example as in the last lab, but you will need some error-handling for when DBpedia is unable to find a match. For instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# Parameter given to spotlight to filter out results with confidence lower than this value&lt;br /&gt;
CONFIDENCE = 0.5&lt;br /&gt;
&lt;br /&gt;
def annotate_entity(entity, filters={&amp;quot;types&amp;quot;:&amp;quot;DBpedia:Person&amp;quot;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = spotlight.annotate(SERVER, entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
    # This catches errors thrown from Spotlight, including when no resource is found in DBpedia&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
		# Implement some error handling here&lt;br /&gt;
	return annotations&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here we use the types-filter with DBpedia:Person, as we only want it to match with people. You can choose to only implement the URIs in the response, or the types as well. An issue here is that &lt;br /&gt;
&lt;br /&gt;
== Useful readings ==&lt;br /&gt;
* [https://github.com/fivethirtyeight/data/tree/master/russia-investigation Information about the dataset]&lt;br /&gt;
* [https://towardsdatascience.com/pandas-dataframe-playing-with-csv-files-944225d19ff Article about working with pandas.DataFrames and CSV]&lt;br /&gt;
* [https://pandas.pydata.org/pandas-docs/stable/reference/frame.html Pandas DataFrame documentation]&lt;br /&gt;
* [https://semanticweb.cs.vu.nl/2009/11/sem/#sem:eventType Simple Event Ontology Descripiton]&lt;br /&gt;
* [http://motools.sourceforge.net/timeline/timeline.html The TimeLine Ontology Description]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=1725</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=1725"/>
		<updated>2022-02-24T12:18:25Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new Python-based lab exercises each week. The old [[Java Labs | Java-based exercises]] are still available if you prefer.&lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 4, from 25/1) &amp;lt;!-- After S1: KG &amp;amp; S2: RDF --&amp;gt;&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 1/2) &amp;lt;!-- After S3: SPARQL --&amp;gt;&lt;br /&gt;
# [[Lab: SPARQL]] (week 6, from 8/2) &amp;lt;!-- After S4: Storing and sharing KGs --&amp;gt;&lt;br /&gt;
# [[Lab: SPARQL Programming]] (week 7, from 15/2) &amp;lt;!-- After S5: Open KGs--&amp;gt;&lt;br /&gt;
# [[Lab: Web APIs and JSON-LD]] (week 8, from 22/2) &amp;lt;!-- After S6: Enterprise KGs --&amp;gt;&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV]] (week 9, from 28/2) &amp;lt;!-- After S8: Vocabularies --&amp;gt;&lt;br /&gt;
# [[Lab: RDFS]] (week 10, from 6/3) &amp;lt;!-- After S7: RDFS --&amp;gt;&lt;br /&gt;
# [[Lab: OWL 1]] (week 11, from 15/3) &amp;lt;!-- After S9: OWL --&amp;gt;&lt;br /&gt;
# [[Lab: Semantic Lifting - XML]] (week 12, from 22/3) &amp;lt;!-- After S10: DL --&amp;gt;&lt;br /&gt;
# [[Lab: More OWL | Lab: OWL 2]] (week 13, from 29/4) &amp;lt;!-- After S11: OWL-DL --&amp;gt;&lt;br /&gt;
# [[Lab: Semantic Lifting - HTML]] (week 14, from 5/4) &amp;lt;!-- After S12: KG embeddings --&amp;gt;&lt;br /&gt;
# Week 15: Easter&lt;br /&gt;
# Week 16: No labs&lt;br /&gt;
# Week 17, from 26/4: Open&lt;br /&gt;
# Week 18, from 3/5: Open&lt;br /&gt;
# Week 19, from 10/5: Open&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1724</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1724"/>
		<updated>2022-02-23T11:58:50Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place (some examples aren&#039;t yet visible).&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
&lt;br /&gt;
===Select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===Select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===Select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===Select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===Select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===Delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===Delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===Check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===Insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
 }&lt;br /&gt;
      &lt;br /&gt;
===Describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==The data are available in this Blazegraph triple store:==&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1723</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1723"/>
		<updated>2022-02-23T11:52:35Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place (some examples aren&#039;t yet visible).&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
&lt;br /&gt;
===Select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===Select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===Select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===Select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===Select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===Delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===Delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===Check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===Insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
 }&lt;br /&gt;
      &lt;br /&gt;
===Describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1722</id>
		<title>Lab: Web APIs and JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1722"/>
		<updated>2022-02-22T13:20:49Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 5: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) Web APIs (RESTful web services) with JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, parse them programmatically, where possible link the resources to established DBpedia ones and finally create a RDFLib graph with the data.&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import json&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
* import spotlight&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
=== Task 1 ===&lt;br /&gt;
Write a small program that queries the Open Notify Astros API (link below) for the people currently in space. Create a graph from the response connecting each astronaut to the craft they are currently on, for instance using http://example.com/onCraft as a property. Also as the space station is not too big, it is safe to assume that two people who spent time on it at the same time know each other, so add this to the graph.&lt;br /&gt;
&lt;br /&gt;
* Astros API url: http://api.open-notify.org/astros.json&lt;br /&gt;
* Documentation: http://open-notify.org/Open-Notify-API/People-In-Space/&lt;br /&gt;
* Requests Quickstart: https://docs.python-requests.org/en/latest/user/quickstart/&lt;br /&gt;
&lt;br /&gt;
The response from the API follows the format&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;message&amp;quot;: &amp;quot;success&amp;quot;,&lt;br /&gt;
    &amp;quot;number&amp;quot;: 7,&lt;br /&gt;
    &amp;quot;people&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Sergey Ryzhikov&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Kate Rubins&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        ...&lt;br /&gt;
    ]&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We only need to think about whats inside the list of the &amp;quot;people&amp;quot;-value.&lt;br /&gt;
To create the graph you can iteratively extract the values of craft and name and add them. As none of the names or craft is a valid URI, they can be crated using the example-namespace.&lt;br /&gt;
&lt;br /&gt;
=== Task 2 ===&lt;br /&gt;
Serialise the graph to JSON-LD, set the context of the JSON-LD object to represent the properties for knows and onCraft.&lt;br /&gt;
&lt;br /&gt;
To do this you need to pip install the json-ld portion of rdflib if you have not already:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install rdflib-jsonld&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== If you have more time ===&lt;br /&gt;
DBpedia Spotlight is a tool for automatically annotating mentions of DBpedia resources in text, providing a solution for linking unstructured information sources to the Linked Open Data cloud through DBpedia.&lt;br /&gt;
&lt;br /&gt;
Build upon the program using the DBpedia Spotlight API (example code below) to use a DBpedia-resource in your graph if one is available. You can add some simple error-handling for cases where no DBpedia resource is found - use an example-entity in stead. Keep in mind that some resources may represent other people with the same name, so try to change the types-parameter so you only get astronauts in return, the confidence-parameter might also help you with this.&lt;br /&gt;
&lt;br /&gt;
The response from DBpedia Spotlight is a list of dictionaries, where each dictionary contains the URI of the resource, its types and some other metadata we will not use now. Set the type of the resouce to the types listed in the response.&lt;br /&gt;
&lt;br /&gt;
==== Example code for DBpedia Spotlight query ====&lt;br /&gt;
First pip install &amp;lt;b&amp;gt;pyspotlight&amp;lt;/b&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import spotlight&lt;br /&gt;
# Note that althoug we import spotlight in python, we need to pip install pyspotlight to get the correct package&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
annotations = spotlight.annotate(SERVER, &amp;quot;str_to_be_annotated&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ Reading and writing with JSON - stackabuse.com]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples Examples]&lt;br /&gt;
* [https://realpython.com/python-requests/ Requests - realpython.com]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=1706</id>
		<title>Lab: SPARQL Programming</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=1706"/>
		<updated>2022-02-15T08:06:05Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab 4 - SPARQL PROGRAMMING ==&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
SPARQL programming in python with SPARQLWrapper and Blazegraph, or alternatively RDFlib.&lt;br /&gt;
These tasks are about programming SPARQL queries and inserts in a python program. &lt;br /&gt;
&lt;br /&gt;
Last week we added triples manually from the web interface. &lt;br /&gt;
&lt;br /&gt;
However, in the majority of cases, we want to program the insertion or updates of triples for our graphs/databases, for instance to handle automatic or scheduled updates. &lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Remember, before you can interact with Blazegraph you have to make sure its running like we did in [https://wiki.uib.no/info216/index.php/Lab:_SPARQL Lab 4].&lt;br /&gt;
*&#039;&#039;&#039;Make a new blazegraph namespace from the blazegraph web-interface and add all the triples that are on the bottom of the page like we did in [https://wiki.uib.no/info216/index.php/Lab:_SPARQL Lab 4]&#039;&#039;&#039;&lt;br /&gt;
Alternatively you can use your own triples if you have them. &lt;br /&gt;
&lt;br /&gt;
The default namespace for blazegraph is &amp;quot;kb&amp;quot;. If you want to add other namespaces you can do it from the web-interface of Blazegraph, from the &amp;quot;Namespace&amp;quot; Tab. Remember to click &amp;quot;Use&amp;quot; on the namespace after you have created it.&lt;br /&gt;
&lt;br /&gt;
The different namespaces for blazegraph acts as seperate graphs/databases. This is especially useful if you are using the UiB link to blazegraph: &amp;quot;i2s.uib.no:8888/bigdata/#splash&amp;quot;, because with your own namespace, only you can select and update your data. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*&#039;&#039;&#039;Redo all the SPARQL queries and updates from [https://wiki.uib.no/info216/index.php/Lab:_SPARQL Lab 4], this time writing a Python program that uses SPARQLWrapper to handle them.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
* SELECT all triples in your graph.&lt;br /&gt;
* SELECT all the interests of Cade.&lt;br /&gt;
* SELECT the city and country of where Emma lives.&lt;br /&gt;
* SELECT only people who are older than 26.&lt;br /&gt;
* SELECT Everyone who graduated with a Bachelor Degree.&lt;br /&gt;
* Use SPARQL Update&#039;s DELETE DATA to delete that fact that Cade is interested in Photography. Run your SPARQL query again to check that the graph has changed.&lt;br /&gt;
&lt;br /&gt;
* Use INSERT DATA to add information about Sergio Pastor, who lives in 4 Carrer del Serpis, 46021 Valencia, Spain. he has a M.Sc. in computer from the University of Valencia from 2008. His areas of expertise include big data, semantic technologies and machine learning.&lt;br /&gt;
&lt;br /&gt;
* Write a SPARQL DELETE/INSERT update to change the name of &amp;quot;University of Valencia&amp;quot; to &amp;quot;Universidad de Valencia&amp;quot; whereever it occurs.&lt;br /&gt;
&lt;br /&gt;
* Write a SPARQL DESCRIBE query to get basic information about Sergio.&lt;br /&gt;
&lt;br /&gt;
* Write a SPARQL CONSTRUCT query that returns that: any city in an address is a cityOf the country of the same address. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==With Blazegraph== &lt;br /&gt;
First, pip install SPARQLWrapper. If you are using Conda: open an Anaconda prompt, activate your environment with &amp;quot;conda activate [name of env]&amp;quot;, and then &amp;quot;pip install sparqlwrapper&amp;quot; in the same prompt. Remember to select this Conda environment in your IDE.&lt;br /&gt;
The most important part is that we need to import a SPARQLWrapper in order to connect to the SPARQL endpoint of Blazegraph.&lt;br /&gt;
 &lt;br /&gt;
When it comes to how to do some queries and updates I recommend scrolling down on this page for help: https://github.com/RDFLib/sparqlwrapper. There are also some examples on our example page.&lt;br /&gt;
&lt;br /&gt;
Remember, before you can program with Blazegraph you have to make sure its running like we did in  [https://wiki.uib.no/info216/index.php/Lab:_SPARQL Lab 4]. Make sure that the URL you use with SPARQLWrapper has the same address and port as the one you get from running it. &lt;br /&gt;
Now you will be able to program queries and updates.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# How to establish connection to Blazegraph endpoint. Also a quick select example.&lt;br /&gt;
&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON&lt;br /&gt;
&lt;br /&gt;
namespace = &amp;quot;kb&amp;quot;&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    SELECT * WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?interest.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;interest&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The different types of queries requires different return formats: &lt;br /&gt;
* SELECT and ASK: a SPARQL Results Document in XML, JSON, or CSV/TSV format.&lt;br /&gt;
* DESCRIBE and CONSTRUCT: an RDF graph serialized, for example, in the TURTLE or RDF/XML syntax, or an equivalent RDF graph serialization.&lt;br /&gt;
Remember to make sure that you can see the changes that take place after your inserts.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Without Blazegraph==&lt;br /&gt;
If you have not been able to run Blazegraph on your own computer yet, you can use the UiB blazegraph service: i2s.uib.no:8888/bigdata/#splash.&lt;br /&gt;
Remember to create your own namespace like said above in the web-interface. &lt;br /&gt;
&lt;br /&gt;
Alternatively, you can&lt;br /&gt;
instead program SPARQL queries directly with RDFlib. &lt;br /&gt;
&lt;br /&gt;
For help, look at the link below: &lt;br /&gt;
&lt;br /&gt;
[https://rdflib.readthedocs.io/en/4.2.0/intro_to_sparql.html Querying with Sparql]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Useful Readings==&lt;br /&gt;
*[https://github.com/RDFLib/sparqlwrapper SPARQLWrapper]&lt;br /&gt;
*[https://rdflib.readthedocs.io/en/4.2.0/intro_to_sparql.html RDFlib - Querying with Sparql]&lt;br /&gt;
&lt;br /&gt;
==SPARQL Queries you can use for tasks==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# SPARQL Queries&lt;br /&gt;
&lt;br /&gt;
prefix ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# SELECT Every triple&lt;br /&gt;
SELECT * WHERE {?s ?p ?o}&lt;br /&gt;
&lt;br /&gt;
# Select the interests of Cade&lt;br /&gt;
SELECT ?interest WHERE {ex:Cade ex:interest ?interest}&lt;br /&gt;
&lt;br /&gt;
# SELECT only people who are older than 26&lt;br /&gt;
SELECT ?person ?age WHERE {?person ex:age ?age. FILTER(?age &amp;gt; 26)}&lt;br /&gt;
&lt;br /&gt;
# SELECT The City and country of Cade&lt;br /&gt;
SELECT ?country ?city WHERE {ex:Cade ex:address ?address. ?address ex:country ?country. ?address ex:city ?city.}&lt;br /&gt;
&lt;br /&gt;
# SELECT Everyone who graduated with a Bachelor Degree.&lt;br /&gt;
SELECT ?person ?level WHERE {?person ex:degree ?degree. ?degree ex:degreeLevel ?level. FILTER(?level=&amp;quot;Bachelor&amp;quot;)}&lt;br /&gt;
&lt;br /&gt;
# DELETE Photography&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
DELETE DATA&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
 ex:Cade ex:interest ex:Photography.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# INSERT Sergio&lt;br /&gt;
&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA&lt;br /&gt;
{&lt;br /&gt;
 ex:Sergio ex:address ex:SergioAddress.&lt;br /&gt;
 ex:SergioAddress ex:city ex:Valencia.&lt;br /&gt;
 ex:SergioAddress ex:street &amp;quot;4 Carrer del Serpis&amp;quot;.&lt;br /&gt;
 ex:SergioAddress ex:postalCode &amp;quot;46021&amp;quot;.&lt;br /&gt;
 ex:SergioAddress ex:country ex:Spain.&lt;br /&gt;
 ex:Sergio ex:address ex:SergioDegree.&lt;br /&gt;
 ex:SergioDegree ex:degreeLevel &amp;quot;Master&amp;quot;.&lt;br /&gt;
 ex:SergioDegree ex:degreeField ex:Computer_Science.&lt;br /&gt;
 ex:SergioDegree ex:degreeYear &amp;quot;2008&amp;quot;.&lt;br /&gt;
 ex:SergioDegree ex:degreeSource ex:University_of_Valencia.&lt;br /&gt;
 ex:Sergio ex:expertise ex:Big_Data.&lt;br /&gt;
 ex:Sergio ex:expertise ex:Semantic_Technologies.&lt;br /&gt;
 ex:Sergio ex:expertise ex:Machine_Learning.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# DELETE Photography&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
DELETE DATA&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
 ex:Cade ex:interest ex:Photography.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
# DELETE/INSERT University&lt;br /&gt;
&lt;br /&gt;
prefix ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {&lt;br /&gt;
  ?s ?p ex:University_of_Valencia.&lt;br /&gt;
}&lt;br /&gt;
INSERT {?s ?p ex:Universidad_de_Valencia.}&lt;br /&gt;
&lt;br /&gt;
WHERE {&lt;br /&gt;
?s ?p ex:University_of_Valencia.}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# Construct&lt;br /&gt;
&lt;br /&gt;
prefix ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {?city ex:cityOf ?country}&lt;br /&gt;
WHERE {?address ex:city ?city. ?address ex:country ?country} &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Triples that you can base your queries on: (turtle format)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Cade a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Berkeley ;&lt;br /&gt;
            ex:country ex:USA ;&lt;br /&gt;
            ex:postalCode &amp;quot;94709&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;1516_Henry_Street&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 27 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Biology ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Bachelor&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_California ;&lt;br /&gt;
            ex:year &amp;quot;2011-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:interest ex:Bird,&lt;br /&gt;
        ex:Ecology,&lt;br /&gt;
        ex:Environmentalism,&lt;br /&gt;
        ex:Photography,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:married ex:Mary ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ex:Canada,&lt;br /&gt;
        ex:France,&lt;br /&gt;
        ex:Germany ;&lt;br /&gt;
    foaf:knows ex:Emma ;&lt;br /&gt;
    foaf:name &amp;quot;Cade_Tracey&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Mary a ex:Student,&lt;br /&gt;
        foaf:Person ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:interest ex:Biology,&lt;br /&gt;
        ex:Chocolate,&lt;br /&gt;
        ex:Hiking .&lt;br /&gt;
&lt;br /&gt;
ex:Emma a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valencia ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46020&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:street &amp;quot;Carrer_de_la Guardia_Civil_20&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Chemistry ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2015-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Air_Pollution,&lt;br /&gt;
        ex:Toxic_Waste,&lt;br /&gt;
        ex:Waste_Management ;&lt;br /&gt;
    ex:interest ex:Bike_Riding,&lt;br /&gt;
        ex:Music,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ( ex:Portugal ex:Italy ex:France ex:Germany ex:Denmark ex:Sweden ) ;&lt;br /&gt;
    foaf:name &amp;quot;Emma_Dominguez&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Meeting1 a ex:Meeting ;&lt;br /&gt;
    ex:date &amp;quot;August, 2014&amp;quot;^^xsd:string ;&lt;br /&gt;
    ex:involved ex:Cade,&lt;br /&gt;
        ex:Emma ;&lt;br /&gt;
    ex:location ex:Paris .&lt;br /&gt;
&lt;br /&gt;
ex:Paris a ex:City ;&lt;br /&gt;
    ex:capitalOf ex:France ;&lt;br /&gt;
    ex:locatedIn ex:France .&lt;br /&gt;
&lt;br /&gt;
ex:France ex:capital ex:Paris .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1705</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1705"/>
		<updated>2022-02-15T07:30:46Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place (some examples aren&#039;t yet visible).&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
&lt;br /&gt;
===Select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===Select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===Select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===Select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===Select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===Delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===Delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===Check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===Insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
 }&lt;br /&gt;
      &lt;br /&gt;
===Describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1704</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1704"/>
		<updated>2022-02-15T07:14:00Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place (some examples aren&#039;t yet visible).&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
&lt;br /&gt;
===Select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===Select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===Select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===Select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===Select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===Delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===Delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===Check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===Insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===Describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1703</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1703"/>
		<updated>2022-02-15T07:12:44Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place (some examples aren&#039;t yet visible).&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1702</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1702"/>
		<updated>2022-02-15T07:09:15Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
    ?address ex:city ?emmaCity .&lt;br /&gt;
    ?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
     FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
    ?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
  ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1701</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1701"/>
		<updated>2022-02-15T07:07:36Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 &lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1700</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1700"/>
		<updated>2022-02-15T07:06:03Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1699</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1699"/>
		<updated>2022-02-14T20:07:52Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
 PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?p ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
 } &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?cadeInterest&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
 } &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
 } &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?age&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
 } &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?person ?degree&lt;br /&gt;
 WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
 } &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
 DELETE DATA&lt;br /&gt;
 {&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
 } &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
 DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
 INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
 WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?s ?o2&lt;br /&gt;
 WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
 DESCRIBE ex:Sergio ?o&lt;br /&gt;
 WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
 CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
 Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
  } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1698</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1698"/>
		<updated>2022-02-14T20:02:12Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1697</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1697"/>
		<updated>2022-02-14T19:55:47Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1696</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1696"/>
		<updated>2022-02-14T19:54:51Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
#&amp;lt;!--&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1688</id>
		<title>SPARQL Examples</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=SPARQL_Examples&amp;diff=1688"/>
		<updated>2022-02-11T15:03:04Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with SPARQL examples as the course progresses.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
== SPARQL Examples from Session 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
The data are available in this Blazegraph triple store:&lt;br /&gt;
[http://sandbox.i2s.uib.no http://sandbox.i2s.uib.no] , but you may need to be inside the UiB network (or on VPN.)&lt;br /&gt;
&lt;br /&gt;
===List properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List types===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?t WHERE {&lt;br /&gt;
   ?s rdf:type ?t .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List authors===&lt;br /&gt;
&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type foaf:Person .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Prefixes used===&lt;br /&gt;
&lt;br /&gt;
The examples below will assume that these are in place.&lt;br /&gt;
&lt;br /&gt;
 PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
 PREFIX dc: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX bibo: &amp;lt;http://purl.org/ontology/bibo/&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
 PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 PREFIX sp: &amp;lt;http://i2s.uib.no/kg4news/science-parse/&amp;gt;&lt;br /&gt;
 PREFIX th: &amp;lt;http://i2s.uib.no/kg4news/theme/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PREFIX ex: &amp;lt;http://example.org/&amp;gt; &lt;br /&gt;
PREFIX xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; &lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===select all triplets in graph===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
} &lt;br /&gt;
===select the interestes of Cade===&lt;br /&gt;
&lt;br /&gt;
SELECT ?cadeInterest&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Cade ex:interest ?cadeInterest .&lt;br /&gt;
} &lt;br /&gt;
===select the country and city where Emma lives===&lt;br /&gt;
&lt;br /&gt;
SELECT ?emmaCity ?emmaCountry&lt;br /&gt;
WHERE {&lt;br /&gt;
    ex:Emma ex:address ?address .&lt;br /&gt;
  	?address ex:city ?emmaCity .&lt;br /&gt;
  	?address ex:country ?emmaCountry .&lt;br /&gt;
} &lt;br /&gt;
===select the people who are over 26 years old===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?age&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:age ?age .&lt;br /&gt;
  	FILTER(?age &amp;gt; 26) .     &lt;br /&gt;
} &lt;br /&gt;
===select people who graduated with Bachelor===&lt;br /&gt;
&lt;br /&gt;
SELECT ?person ?degree&lt;br /&gt;
WHERE {&lt;br /&gt;
    ?person ex:degree ?degree .&lt;br /&gt;
  	?degree ex:degreeLevel &amp;quot;Bachelor&amp;quot; .&lt;br /&gt;
          &lt;br /&gt;
} &lt;br /&gt;
===delete cades photography interest===&lt;br /&gt;
&lt;br /&gt;
DELETE DATA&lt;br /&gt;
{&lt;br /&gt;
    ex:Cade ex:interest ex:Photography .&lt;br /&gt;
} &lt;br /&gt;
===delete and insert university of valencia===&lt;br /&gt;
&lt;br /&gt;
DELETE { ?s ?p ex:University_of_Valencia }&lt;br /&gt;
INSERT { ?s ?p ex:Universidad_de_Valencia }&lt;br /&gt;
WHERE  { ?s ?p ex:University_of_Valencia } &lt;br /&gt;
&lt;br /&gt;
===check if the deletion worked===&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o2&lt;br /&gt;
WHERE  { &lt;br /&gt;
  ?s ex:degree ?o .&lt;br /&gt;
  ?o ex:degreeSource ?o2 .&lt;br /&gt;
       	}&lt;br /&gt;
&lt;br /&gt;
===insert Sergio===&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
  ex:Sergio a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valenciay ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46021&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;4_Carrer_del_Serpis&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Computer_science ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2008&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Big_data,&lt;br /&gt;
        ex:Semantic_technologies,&lt;br /&gt;
        ex:Machine_learning;&lt;br /&gt;
    foaf:name &amp;quot;Sergio_Pastor&amp;quot;^^xsd:string .&lt;br /&gt;
}&lt;br /&gt;
      &lt;br /&gt;
===describe Sergio===&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ex:Sergio ?o&lt;br /&gt;
WHERE {&lt;br /&gt;
  ex:Sergio ?p ?o .&lt;br /&gt;
   ?o ?p2 ?o2 .&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===construct that any city is in the country in an address=== &lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {?city ex:locatedIn ?country}&lt;br /&gt;
Where {&lt;br /&gt;
  ?s rdf:type ex:Address .&lt;br /&gt;
  ?s ex:city ?city .&lt;br /&gt;
  ?s ex:country ?country.&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
 SELECT DISTINCT ?p WHERE {&lt;br /&gt;
   ?s rdf:type ss:Paper .&lt;br /&gt;
   ?s ?p ?o .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===Explain all types and properties===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?pt ?e WHERE {&lt;br /&gt;
   ?pt rdfs:comment ?e .&lt;br /&gt;
 } LIMIT 100&lt;br /&gt;
&lt;br /&gt;
===List main papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Add this to show datatypes!&lt;br /&gt;
   BIND ( DATATYPE(?year) AS ?type )&lt;br /&gt;
&lt;br /&gt;
Add this to only show years with the right type.&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
&lt;br /&gt;
===Group and count main papers by year===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?year (COUNT(?paper) AS ?count) WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
 GROUP BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order the results&lt;br /&gt;
 ORDER BY ?year&lt;br /&gt;
&lt;br /&gt;
Add this to order and only show years with more than 5 papers.&lt;br /&gt;
 HAVING (?count &amp;gt; 5)&lt;br /&gt;
 ORDER BY DESC(?count)&lt;br /&gt;
&lt;br /&gt;
===Show papers===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?paper ?year WHERE {&lt;br /&gt;
 &lt;br /&gt;
   ?paper rdf:type kg:MainPaper .&lt;br /&gt;
   ?paper dc:date ?year .&lt;br /&gt;
   FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Change last lines to show papers without an xsd:gYear too.&lt;br /&gt;
   OPTIONAL {&lt;br /&gt;
       ?paper dc:date ?year .&lt;br /&gt;
       FILTER ( DATATYPE(?year) = xsd:gYear )&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
===Alternative values for variables===&lt;br /&gt;
&lt;br /&gt;
 SELECT ?p ?n ?year WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?a .&lt;br /&gt;
   ?a foaf:name ?n .&lt;br /&gt;
   ?p dc:date ?year .&lt;br /&gt;
   FILTER ( CONTAINS( ?n, ?str ) )&lt;br /&gt;
   FILTER ( CONTAINS( STR(?year), ?yr) )&lt;br /&gt;
  &lt;br /&gt;
   VALUES ?str { &amp;quot;Andreas&amp;quot; &amp;quot;David&amp;quot; }&lt;br /&gt;
   VALUES ?yr { &amp;quot;2020&amp;quot; &amp;quot;2019&amp;quot; }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Property paths (composite properties)===&lt;br /&gt;
&lt;br /&gt;
This query:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor ?c .&lt;br /&gt;
   ?c foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be simplified by eliminating ?c:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Can be further simplified by first reversing rdf:type:&lt;br /&gt;
 SELECT ?p ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type ?p .&lt;br /&gt;
   ?p dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
...and the eliminating ?p:&lt;br /&gt;
 SELECT ?n WHERE {&lt;br /&gt;
   kg:MainPaper ^rdf:type / dc:contributor / foaf:name ?n .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Retrieve titles of papers that mention SPARQL===&lt;br /&gt;
&lt;br /&gt;
Get papers with topics labelled &amp;quot;SPARQL&amp;quot;:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Some labels also go via a theme:&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
We can get both using a path with an optional element (the &#039;?&#039;):&lt;br /&gt;
 SELECT ?t WHERE {&lt;br /&gt;
   ?t ^dc:title / dc:subject / th:theme? / skos:prefLabel &amp;quot;SPARQL&amp;quot; .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Using an external SPARQL endpoint===&lt;br /&gt;
&lt;br /&gt;
We limit to a single label to avoid time-outs and rate limitations:&lt;br /&gt;
 SELECT ?a ?n ?r WHERE {&lt;br /&gt;
   ?a rdf:type ss:Topic .&lt;br /&gt;
   ?a skos:prefLabel ?n .&lt;br /&gt;
   FILTER ( ?n = &amp;quot;SPARQL&amp;quot; )&lt;br /&gt;
   BIND ( STRLANG( ?n, &amp;quot;en&amp;quot; ) AS ?n2 )&lt;br /&gt;
     SERVICE &amp;lt;https://dbpedia.org/sparql&amp;gt; {&lt;br /&gt;
     ?r rdfs:label ?n2 .&lt;br /&gt;
     }&lt;br /&gt;
 } LIMIT 1&lt;br /&gt;
&lt;br /&gt;
===Insert 4-digit years for all main papers===&lt;br /&gt;
&lt;br /&gt;
Main papers that do not have an xsd:gYear:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:gYear )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Show the datatypes:&lt;br /&gt;
 SELECT * WHERE {&lt;br /&gt;
  &lt;br /&gt;
   ?p rdf:type kg:MainPaper .&lt;br /&gt;
   ?p dc:date ?d .&lt;br /&gt;
   FILTER ( DATATYPE(?d) = xsd:dateTime )&lt;br /&gt;
   BIND ( year( ?d ) AS ?dt )&lt;br /&gt;
  &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Insert 4-digit years:&lt;br /&gt;
 INSERT { ?paper dc:date ?year } &lt;br /&gt;
 WHERE {&lt;br /&gt;
   &lt;br /&gt;
  ?paper rdf:type kg:MainPaper .&lt;br /&gt;
  ?paper dc:date ?date .&lt;br /&gt;
   FILTER( DATATYPE(?date) != xsd:gYear )&lt;br /&gt;
   BIND ( YEAR(?date) AS ?year ) &lt;br /&gt;
   &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
(Actually, these years are xsd:integer- s, not quite xsd:gYear-s.)&lt;br /&gt;
&lt;br /&gt;
== SPARQL Examples from Session 7: RDFS==&lt;br /&gt;
&lt;br /&gt;
===Turn on inference!===&lt;br /&gt;
&lt;br /&gt;
Make sure inference is on in your triple store, or that you compute closures if you run this in Python with rdflib and OWL-RL.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Blazegraph&#039;&#039;&#039;, create a new &amp;quot;Namespace&amp;quot; with the &amp;quot;Inference&amp;quot; box checked. &lt;br /&gt;
Remember to &amp;quot;Use&amp;quot; the new namespace.&lt;br /&gt;
&lt;br /&gt;
In &#039;&#039;&#039;Python&#039;&#039;&#039;, install the [https://owl-rl.readthedocs.io/en/latest/ OWL-RL package] (&#039;&#039;pip install owlrl&#039;&#039;). &lt;br /&gt;
Explicitly compute RDFS closure like this:&lt;br /&gt;
 import owlrl.RDFSClosure&lt;br /&gt;
 &lt;br /&gt;
 ...&lt;br /&gt;
 &lt;br /&gt;
 rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
 rdfs.closure()&lt;br /&gt;
 rdfs.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
===rdfs:subClassOf entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:Author rdfs:subClassOf foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TimBernersLee rdf:type foaf:Person . &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===rdfs:domain entailment===&lt;br /&gt;
&lt;br /&gt;
Update:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 INSERT DATA {&lt;br /&gt;
     kg:TimBernersLee rdf:type kg:Author .&lt;br /&gt;
     kg:TheSemanticWeb dcterm:contributor kg:TimBernersLee .&lt;br /&gt;
     dcterm:contributor rdfs:domain kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Query:&lt;br /&gt;
 PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
 PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
 PREFIX dcterm: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
 PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 ASK {&lt;br /&gt;
     kg:TheSemanticWeb rdf:type kg:Paper .&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==OWL Ontologies==&lt;br /&gt;
&lt;br /&gt;
The following files contain an ontology for the knowledge graph used in this page:&lt;br /&gt;
* Small: [[:File:small-kg4news-ontology.txt]]&lt;br /&gt;
* Full:  [[:File:kg4news-ontology.txt]]&lt;br /&gt;
&lt;br /&gt;
Rename them from &#039;.txt.&#039; to &#039;.ttl&#039; after you download them.&lt;br /&gt;
&lt;br /&gt;
You can&lt;br /&gt;
* view the ontologies online using [http://www.visualdataweb.de/webvowl/ WebVOWL] or &lt;br /&gt;
* download the [https://protege.stanford.edu/products.php#desktop-protege Protegé-OWL] ontology editor.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=1686</id>
		<title>Lab: SPARQL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=1686"/>
		<updated>2022-02-08T08:57:11Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Lab 3: SPARQL / Blazegraph=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
* Setting up the Blazegraph graph database. Previously we have only stored our triples in memory, which is not persistent. &lt;br /&gt;
* SPARQL queries and updates. We use SPARQL to retrieve of update triples in our databases/graphs of triples&lt;br /&gt;
&lt;br /&gt;
==Installing the Blazegraph database on your own computer==&lt;br /&gt;
Download Blazegraph (blazegraph.jar) from here: [https://blazegraph.com/ https://blazegraph.com/]&lt;br /&gt;
I recommend placing blazegraph.jar in the same folder of your python project for the labs. &lt;br /&gt;
Navigate to the folder of blazegraph.jar in your commandline/terminal using cd. (cd C:\Users\marti\info216 for me as an example). Now run this command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
java -server -Xmx4g -jar blazegraph.jar&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
You might have to install java 64-bit JDK if you have problems running blazegraph. You can do it from  this link: &lt;br /&gt;
&amp;quot;https://www.oracle.com/technetwork/java/javase/downloads/&amp;quot;&lt;br /&gt;
If you get an &amp;quot;Address already in use&amp;quot; error, this is likely because blazegraph has been terminated improperly. Either restart the terminal-session or try to run this command instead: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
java -server -Xmx4g -Djetty.port=19999 -jar blazegraph.jar &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
This changes the port of the blazegraph server.&lt;br /&gt;
&lt;br /&gt;
If you have trouble installing Blazegraph you can use this link for now: &amp;quot;http://sandbox.i2s.uib.no/bigdata/&amp;quot;.&lt;br /&gt;
This is the same blazegraph interface, but its stored in the cloud and only be used on the UiB network. You may be able to access it without connecting to the UiB Network, but if you are unable to access the endpoint try connecting via the VPN. Instructions [https://hjelp.uib.no/tas/public/ssp/content/detail/service?unid=a566dafec92a4d35bba974f0733f3663 here].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If it works it should now display an url like: &amp;quot;http://10.0.0.13:9999/blazegraph/&amp;quot;. Open this in a browser. &lt;br /&gt;
You can now run SPARQL queries and updates and load RDF graphs from your file into Blazegraph.&lt;br /&gt;
In the update tab, load RDF data (select type below) and then paste the contents of your turtle/.txt file to add them all at once to the database. If you have not serialized your graph from lab 2 yet, you can use the triples on the bottom of the page instead. Just copy and paste them into the Update section.&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Write the following SPARQL queries: &lt;br /&gt;
&lt;br /&gt;
* SELECT all triples in your graph. &lt;br /&gt;
* SELECT all the interests of Cade.&lt;br /&gt;
* SELECT the city and country of where Emma lives.&lt;br /&gt;
* SELECT only people who are older than 26.&lt;br /&gt;
* SELECT Everyone who graduated with a Bachelor Degree. &lt;br /&gt;
&lt;br /&gt;
Use SPARQL Update&#039;s DELETE DATA to delete that fact that Cade is interested in Photography. Run your SPARQL query again to check that the graph has changed.&lt;br /&gt;
&lt;br /&gt;
Use INSERT DATA to add information about Sergio Pastor, who lives in 4 Carrer del Serpis, 46021 Valencia, Spain. he has a M.Sc. in computer from the University of Valencia from 2008. His areas of expertise include big data, semantic technologies and machine learning.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL DELETE/INSERT update to change the name of &amp;quot;University of Valencia&amp;quot; to &amp;quot;Universidad de Valencia&amp;quot; whereever it occurs.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL DESCRIBE query to get basic information about Sergio.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL CONSTRUCT query that returns that: any city in an address is a cityOf the country of the same address.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
Redo all the above steps, this time writing a Python/RDFlib program. This will be the topic of lab 6.&lt;br /&gt;
You can look at the python example page to see how to connect to your blazegraph endpoint in Python and how to perform some basic queries.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Useful Links==&lt;br /&gt;
[https://wiki.uib.no/info216/index.php/File:S03-SPARQL-13.pdf Lecture Notes]&lt;br /&gt;
&lt;br /&gt;
[https://www.w3.org/TR/sparql11-query/ SPARQL Query Documentation]&lt;br /&gt;
&lt;br /&gt;
[http://www.w3.org/TR/sparql11-update/ SPARQL Update Documentation]&lt;br /&gt;
&lt;br /&gt;
==Triples that you can base your queries on: (turtle format)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Cade a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Berkeley ;&lt;br /&gt;
            ex:country ex:USA ;&lt;br /&gt;
            ex:postalCode &amp;quot;94709&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;1516_Henry_Street&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 27 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Biology ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Bachelor&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_California ;&lt;br /&gt;
            ex:year &amp;quot;2011-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:interest ex:Bird,&lt;br /&gt;
        ex:Ecology,&lt;br /&gt;
        ex:Environmentalism,&lt;br /&gt;
        ex:Photography,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:married ex:Mary ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ex:Canada,&lt;br /&gt;
        ex:France,&lt;br /&gt;
        ex:Germany ;&lt;br /&gt;
    foaf:knows ex:Emma ;&lt;br /&gt;
    foaf:name &amp;quot;Cade_Tracey&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Mary a ex:Student,&lt;br /&gt;
        foaf:Person ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:interest ex:Biology,&lt;br /&gt;
        ex:Chocolate,&lt;br /&gt;
        ex:Hiking .&lt;br /&gt;
&lt;br /&gt;
ex:Emma a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valencia ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46020&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:street &amp;quot;Carrer_de_la Guardia_Civil_20&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Chemistry ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2015-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Air_Pollution,&lt;br /&gt;
        ex:Toxic_Waste,&lt;br /&gt;
        ex:Waste_Management ;&lt;br /&gt;
    ex:interest ex:Bike_Riding,&lt;br /&gt;
        ex:Music,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ( ex:Portugal ex:Italy ex:France ex:Germany ex:Denmark ex:Sweden ) ;&lt;br /&gt;
    foaf:name &amp;quot;Emma_Dominguez&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Meeting1 a ex:Meeting ;&lt;br /&gt;
    ex:date &amp;quot;August, 2014&amp;quot;^^xsd:string ;&lt;br /&gt;
    ex:involved ex:Cade,&lt;br /&gt;
        ex:Emma ;&lt;br /&gt;
    ex:location ex:Paris .&lt;br /&gt;
&lt;br /&gt;
ex:Paris a ex:City ;&lt;br /&gt;
    ex:capitalOf ex:France ;&lt;br /&gt;
    ex:locatedIn ex:France .&lt;br /&gt;
&lt;br /&gt;
ex:France ex:capital ex:Paris .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=1685</id>
		<title>Lab: SPARQL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=1685"/>
		<updated>2022-02-08T08:49:04Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Lab 3: SPARQL / Blazegraph=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
* Setting up the Blazegraph graph database. Previously we have only stored our triples in memory, which is not persistent. &lt;br /&gt;
* SPARQL queries and updates. We use SPARQL to retrieve of update triples in our databases/graphs of triples&lt;br /&gt;
&lt;br /&gt;
==Installing the Blazegraph database on your own computer==&lt;br /&gt;
Download Blazegraph (blazegraph.jar) from here: [https://blazegraph.com/ https://blazegraph.com/]&lt;br /&gt;
I recommend placing blazegraph.jar in the same folder of your python project for the labs. &lt;br /&gt;
Navigate to the folder of blazegraph.jar in your commandline/terminal using cd. (cd C:\Users\marti\info216 for me as an example). Now run this command:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
java -server -Xmx4g -jar blazegraph.jar&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
You might have to install java 8 64-bit JDK if you have problems running blazegraph. You can do it from  this link: &lt;br /&gt;
&amp;quot;https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html&amp;quot;&lt;br /&gt;
If you get an &amp;quot;Address already in use&amp;quot; error, this is likely because blazegraph has been terminated improperly. Either restart the terminal-session or try to run this command instead: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
java -server -Xmx4g -Djetty.port=19999 -jar blazegraph.jar &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
This changes the port of the blazegraph server.&lt;br /&gt;
&lt;br /&gt;
If you have trouble installing Blazegraph you can use this link for now: &amp;quot;http://sandbox.i2s.uib.no/bigdata/&amp;quot;.&lt;br /&gt;
This is the same blazegraph interface, but its stored in the cloud and only be used on the UiB network. You may be able to access it without connecting to the UiB Network, but if you are unable to access the endpoint try connecting via the VPN. Instructions [https://hjelp.uib.no/tas/public/ssp/content/detail/service?unid=a566dafec92a4d35bba974f0733f3663 here].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If it works it should now display an url like: &amp;quot;http://10.0.0.13:9999/blazegraph/&amp;quot;. Open this in a browser. &lt;br /&gt;
You can now run SPARQL queries and updates and load RDF graphs from your file into Blazegraph.&lt;br /&gt;
In the update tab, load RDF data (select type below) and then paste the contents of your turtle/.txt file to add them all at once to the database. If you have not serialized your graph from lab 2 yet, you can use the triples on the bottom of the page instead. Just copy and paste them into the Update section.&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Write the following SPARQL queries: &lt;br /&gt;
&lt;br /&gt;
* SELECT all triples in your graph. &lt;br /&gt;
* SELECT all the interests of Cade.&lt;br /&gt;
* SELECT the city and country of where Emma lives.&lt;br /&gt;
* SELECT only people who are older than 26.&lt;br /&gt;
* SELECT Everyone who graduated with a Bachelor Degree. &lt;br /&gt;
&lt;br /&gt;
Use SPARQL Update&#039;s DELETE DATA to delete that fact that Cade is interested in Photography. Run your SPARQL query again to check that the graph has changed.&lt;br /&gt;
&lt;br /&gt;
Use INSERT DATA to add information about Sergio Pastor, who lives in 4 Carrer del Serpis, 46021 Valencia, Spain. he has a M.Sc. in computer from the University of Valencia from 2008. His areas of expertise include big data, semantic technologies and machine learning.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL DELETE/INSERT update to change the name of &amp;quot;University of Valencia&amp;quot; to &amp;quot;Universidad de Valencia&amp;quot; whereever it occurs.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL DESCRIBE query to get basic information about Sergio.&lt;br /&gt;
&lt;br /&gt;
Write a SPARQL CONSTRUCT query that returns that: any city in an address is a cityOf the country of the same address.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
Redo all the above steps, this time writing a Python/RDFlib program. This will be the topic of lab 6.&lt;br /&gt;
You can look at the python example page to see how to connect to your blazegraph endpoint in Python and how to perform some basic queries.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Useful Links==&lt;br /&gt;
[https://wiki.uib.no/info216/index.php/File:S03-SPARQL-13.pdf Lecture Notes]&lt;br /&gt;
&lt;br /&gt;
[https://www.w3.org/TR/sparql11-query/ SPARQL Query Documentation]&lt;br /&gt;
&lt;br /&gt;
[http://www.w3.org/TR/sparql11-update/ SPARQL Update Documentation]&lt;br /&gt;
&lt;br /&gt;
==Triples that you can base your queries on: (turtle format)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Cade a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Berkeley ;&lt;br /&gt;
            ex:country ex:USA ;&lt;br /&gt;
            ex:postalCode &amp;quot;94709&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:state ex:California ;&lt;br /&gt;
            ex:street &amp;quot;1516_Henry_Street&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 27 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Biology ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Bachelor&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_California ;&lt;br /&gt;
            ex:year &amp;quot;2011-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:interest ex:Bird,&lt;br /&gt;
        ex:Ecology,&lt;br /&gt;
        ex:Environmentalism,&lt;br /&gt;
        ex:Photography,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:married ex:Mary ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ex:Canada,&lt;br /&gt;
        ex:France,&lt;br /&gt;
        ex:Germany ;&lt;br /&gt;
    foaf:knows ex:Emma ;&lt;br /&gt;
    foaf:name &amp;quot;Cade_Tracey&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Mary a ex:Student,&lt;br /&gt;
        foaf:Person ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:characteristic ex:Kind ;&lt;br /&gt;
    ex:interest ex:Biology,&lt;br /&gt;
        ex:Chocolate,&lt;br /&gt;
        ex:Hiking .&lt;br /&gt;
&lt;br /&gt;
ex:Emma a foaf:Person ;&lt;br /&gt;
    ex:address [ a ex:Address ;&lt;br /&gt;
            ex:city ex:Valencia ;&lt;br /&gt;
            ex:country ex:Spain ;&lt;br /&gt;
            ex:postalCode &amp;quot;46020&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:street &amp;quot;Carrer_de_la Guardia_Civil_20&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:age 26 ;&lt;br /&gt;
    ex:degree [ ex:degreeField ex:Chemistry ;&lt;br /&gt;
            ex:degreeLevel &amp;quot;Master&amp;quot;^^xsd:string ;&lt;br /&gt;
            ex:degreeSource ex:University_of_Valencia ;&lt;br /&gt;
            ex:year &amp;quot;2015-01-01&amp;quot;^^xsd:gYear ] ;&lt;br /&gt;
    ex:expertise ex:Air_Pollution,&lt;br /&gt;
        ex:Toxic_Waste,&lt;br /&gt;
        ex:Waste_Management ;&lt;br /&gt;
    ex:interest ex:Bike_Riding,&lt;br /&gt;
        ex:Music,&lt;br /&gt;
        ex:Travelling ;&lt;br /&gt;
    ex:meeting ex:Meeting1 ;&lt;br /&gt;
    ex:visit ( ex:Portugal ex:Italy ex:France ex:Germany ex:Denmark ex:Sweden ) ;&lt;br /&gt;
    foaf:name &amp;quot;Emma_Dominguez&amp;quot;^^xsd:string .&lt;br /&gt;
&lt;br /&gt;
ex:Meeting1 a ex:Meeting ;&lt;br /&gt;
    ex:date &amp;quot;August, 2014&amp;quot;^^xsd:string ;&lt;br /&gt;
    ex:involved ex:Cade,&lt;br /&gt;
        ex:Emma ;&lt;br /&gt;
    ex:location ex:Paris .&lt;br /&gt;
&lt;br /&gt;
ex:Paris a ex:City ;&lt;br /&gt;
    ex:capitalOf ex:France ;&lt;br /&gt;
    ex:locatedIn ex:France .&lt;br /&gt;
&lt;br /&gt;
ex:France ex:capital ex:Paris .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_RDF_programming_with_RDFlib&amp;diff=1680</id>
		<title>Lab: RDF programming with RDFlib</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_RDF_programming_with_RDFlib&amp;diff=1680"/>
		<updated>2022-02-04T14:53:53Z</updated>

		<summary type="html">&lt;p&gt;Xin004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 2: RDF programming with RDFlib=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
* Basic RDF graph programming with RDFlib.&lt;br /&gt;
* Simple reading/writing from/to file.&lt;br /&gt;
* Simple looping through graph&lt;br /&gt;
&lt;br /&gt;
==Classes/interfaces==&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
&lt;br /&gt;
from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Methods:&lt;br /&gt;
Graph - add(), remove(), triples(), serialize(), parse(), bind()&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Consider the following situation:&lt;br /&gt;
&amp;quot;Cade lives in 1516 Henry Street, Berkeley, California 94709,&lt;br /&gt;
USA. He has a B.Sc. in biology from the University of California,&lt;br /&gt;
Berkeley from 2011. His interests include birds, ecology, the&lt;br /&gt;
environment, photography and travelling. He has visited Canada and&lt;br /&gt;
France. Emma Dominguez lives in Carrer de la Guardia Civil 20, 46020&lt;br /&gt;
Valencia, Spain. She has a M.Sc. in chemistry from the University of&lt;br /&gt;
Valencia from 2015. Her areas of expertise include waste management,&lt;br /&gt;
toxic waste, air pollution. Her interests include bike riding, music&lt;br /&gt;
and travelling. She has visited Portugal, Italy, France, Germany,&lt;br /&gt;
Denmark and Sweden. Cade knows Emma. They met in Paris in August&lt;br /&gt;
2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Create a graph in RDFlib with triples corresponding to the text above. Build on the graph from lab 1. Use your own URIs when you need to (like &amp;quot;http://example.org/&amp;quot;), but try to use terms from vocabularies such as FOAF, RDF, XSD, and others.&lt;br /&gt;
&lt;br /&gt;
Write out your graph to the console. This seems to be the cleanest way of printing the graph to me:&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;))&lt;br /&gt;
But try all the following formats: &amp;quot;turtle&amp;quot;, &amp;quot;n3&amp;quot;, &amp;quot;nt&amp;quot;, &amp;quot;json-ld&amp;quot;, &amp;quot;xml&amp;quot;. How do they differ? What is the default?&lt;br /&gt;
&lt;br /&gt;
Write your graph to a file. To do this, you can simply use the location parameter e.g: g.serialize(destination=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
Look at the file and edit it so that Cade has also visited Germany and so that Emma is 26 years old. &lt;br /&gt;
&lt;br /&gt;
Create a new program that reads your graph in again from the file and&lt;br /&gt;
writes it to the console. e.g g.parse(location=&amp;quot;triples.txt&amp;quot;, format=&amp;quot;turtle&amp;quot;) &lt;br /&gt;
Check that your new data is there!&lt;br /&gt;
&lt;br /&gt;
Continuing with either your first or second program, write a loop that&lt;br /&gt;
goes through all the triples in the graph and prints them to the&lt;br /&gt;
console.&lt;br /&gt;
&lt;br /&gt;
Change the loop so that (a) it only loops through triples about&lt;br /&gt;
Emma (b) it only loops through triples involving the names of&lt;br /&gt;
people. &lt;br /&gt;
&lt;br /&gt;
Remove all triples about Mary using graph.remove(). (triples of Mary are from lab 1)&lt;br /&gt;
&lt;br /&gt;
==Useful Links==&lt;br /&gt;
&lt;br /&gt;
[https://rdflib.readthedocs.io/en/stable/index.html rdflib documentation]:&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html Creating Triples]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_graphs.html Navigating Graphs]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_parsing.html Parsing]&lt;br /&gt;
&lt;br /&gt;
[https://wiki.uib.no/info216/index.php/File:S02-RDF-9.pdf Lecture Notes]&lt;/div&gt;</summary>
		<author><name>Xin004</name></author>
	</entry>
</feed>