<?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=Say004</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=Say004"/>
	<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/Special:Contributions/Say004"/>
	<updated>2026-05-24T13:59:42Z</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=1388</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1388"/>
		<updated>2020-05-18T11:31:37Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/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;
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;
== Lecture 5: 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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1387</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1387"/>
		<updated>2020-05-18T11:17:08Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1382</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1382"/>
		<updated>2020-05-11T11:25:53Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1375</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1375"/>
		<updated>2020-05-03T11:24:32Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1374</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1374"/>
		<updated>2020-05-03T11:23:29Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1373</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1373"/>
		<updated>2020-05-03T11:21:08Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&lt;br /&gt;
&lt;br /&gt;
===Using paramters/variables in rdflib queries==&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;/syntachighlight&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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1372</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1372"/>
		<updated>2020-05-03T07:16:26Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1371</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1371"/>
		<updated>2020-05-03T07:11:40Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1370</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1370"/>
		<updated>2020-05-03T07:10:03Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
===Retrieving data from Wikidata with SparqlWrapper===&lt;br /&gt;
&lt;br /&gt;
results = sparql.query()&lt;br /&gt;
print(results.response.read())&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1365</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1365"/>
		<updated>2020-04-24T10:27:11Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1364</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1364"/>
		<updated>2020-04-24T10:25:39Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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;
# 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, ex.grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
IMPORANT: It seems owlrl is unable to reason with OWL Restrictions and perhaps other concepts as well.&lt;br /&gt;
There is a python library for better OWL reasoning called Owlready if you want to reason with restrictions.  &lt;br /&gt;
Below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
What has changed about e.g Cade after using owlrl?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# # Write owl file before any reasoned triples&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Write owl file that includes reasoned triples&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1363</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1363"/>
		<updated>2020-04-24T10:25:11Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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;
# 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, ex.grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
IMPORANT: It seems owlrl is unable to reason with OWL Restrictions and perhaps other concepts as well.&lt;br /&gt;
There is a python library for better OWL reasoning called Owlready if you want to reason with restrictions.  &lt;br /&gt;
e.g below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
What has changed about e.g Cade after using owlrl?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# # Write owl file before any reasoned triples&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# Write owl file that includes reasoned triples&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1362</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1362"/>
		<updated>2020-04-24T09:40:37Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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 person 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1361</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1361"/>
		<updated>2020-04-24T09:38:52Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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 person 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;
# each Employee has exactly one birthday&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.employeeBirthday))&lt;br /&gt;
g.add((br, OWL.cardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Employee, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# OR like this, but the first is more powerful:&lt;br /&gt;
g.add((ex.employeeBirthDay, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.employeeBirthDay, RDFS.domain, OWL.Employee))&lt;br /&gt;
&lt;br /&gt;
# e.g if using restriction (first method):&lt;br /&gt;
g.add((ex.Cade, ex.employeeBirthday, Literal(&amp;quot;01-01-95&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Person))&lt;br /&gt;
# then we can use owl reasoning to know that Cade is an employee without specifying it because he fullfills the restriction and Person requirements. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1360</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1360"/>
		<updated>2020-04-24T09:38:07Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;
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 person 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;
# each Employee has exactly one birthday&lt;br /&gt;
br = BNode()&lt;br /&gt;
g.add((br, RDF.type, OWL.Restriction))&lt;br /&gt;
g.add((br, OWL.onProperty, ex.employeeBirthday))&lt;br /&gt;
g.add((br, OWL.cardinality, Literal(1)))&lt;br /&gt;
bi = BNode()&lt;br /&gt;
Collection(g, bi, [ex.Person, br])&lt;br /&gt;
g.add((ex.Employee, OWL.intersectionOf, bi))&lt;br /&gt;
&lt;br /&gt;
# OR like this, but the first is more powerful:&lt;br /&gt;
g.add((ex.employeeBirthDay, RDF.type, OWL.FunctionalProperty))&lt;br /&gt;
g.add((ex.employeeBirthDay, RDFS.domain, OWL.Employee))&lt;br /&gt;
&lt;br /&gt;
# e.g if using restriction (first method):&lt;br /&gt;
g.add((ex.Cade, ex.employeeBirthday, Literal(&amp;quot;01-01-95&amp;quot;)))&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Person))&lt;br /&gt;
# then we can use owl reasoning to know that Cade is an employee without specifying it because he fullfills the restriction and Person requirements. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1359</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1359"/>
		<updated>2020-04-24T08:51:08Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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;
# 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, ex.grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
e.g below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
What has changed about e.g Cade after using owlrl?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# print without reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# # Print with reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1356</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=1356"/>
		<updated>2020-04-22T10:15:33Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph, Namespace, RDFS&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
e.g http://api.geonames.org/weatherJSON?formatted=true&amp;amp;north=44.1&amp;amp;south=-9.9&amp;amp;east=-22.4&amp;amp;west=55.2&amp;amp;username=demo&amp;amp;style=full&lt;br /&gt;
&lt;br /&gt;
Which approach do you find to be easiest?&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&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;
from rdflib import Graph, Namespace, RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
dbp = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;geo&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
#start here with making API requests: &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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1355</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=1355"/>
		<updated>2020-04-22T10:13:54Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
e.g http://api.geonames.org/weatherJSON?formatted=true&amp;amp;north=44.1&amp;amp;south=-9.9&amp;amp;east=-22.4&amp;amp;west=55.2&amp;amp;username=demo&amp;amp;style=full&lt;br /&gt;
&lt;br /&gt;
Which approach do you find to be easiest?&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&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;
from rdflib import Graph, Namespace, RDFS&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
dbp = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;geo&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
#start here with making API requests: &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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1354</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=1354"/>
		<updated>2020-04-22T10:13:00Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
e.g http://api.geonames.org/weatherJSON?formatted=true&amp;amp;north=44.1&amp;amp;south=-9.9&amp;amp;east=-22.4&amp;amp;west=55.2&amp;amp;username=demo&amp;amp;style=full&lt;br /&gt;
&lt;br /&gt;
Which approach do you find to be easiest?&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&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;
from rdflib import Graph, Namespace, RDFS&lt;br /&gt;
g = Graph()&lt;br /&gt;
dbp = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
geo = Namespace(&amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;dbp&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;geo&amp;quot;, ex)&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1353</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=1353"/>
		<updated>2020-04-22T09:34:20Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
e.g http://api.geonames.org/weatherJSON?formatted=true&amp;amp;north=44.1&amp;amp;south=-9.9&amp;amp;east=-22.4&amp;amp;west=55.2&amp;amp;username=demo&amp;amp;style=full&lt;br /&gt;
&lt;br /&gt;
Which approach do you find to be easiest?&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1352</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=1352"/>
		<updated>2020-04-22T08:15:26Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
e.g http://api.geonames.org/weatherJSON?formatted=true&amp;amp;north=44.1&amp;amp;south=-9.9&amp;amp;east=-22.4&amp;amp;west=55.2&amp;amp;username=demo&amp;amp;style=full&lt;br /&gt;
&lt;br /&gt;
Which approach do you find to be easiest?&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1351</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=1351"/>
		<updated>2020-04-22T08:11:05Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without making a context. This mean you must iterate/access each data point that you need with the json library.&lt;br /&gt;
&lt;br /&gt;
If you can, go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1350</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=1350"/>
		<updated>2020-04-22T07:42:38Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without using a context. &lt;br /&gt;
&lt;br /&gt;
If you can, go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1349</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=1349"/>
		<updated>2020-04-22T07:42:17Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
Try to download a new JSON from a different API and lift its data to the rdflib Graph, without using context.&lt;br /&gt;
&lt;br /&gt;
If you can, go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1348</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1348"/>
		<updated>2020-04-19T12:39:40Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
==Semantic Lifting - HTML==&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 API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1347</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1347"/>
		<updated>2020-04-19T11:06:05Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, ex.grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
e.g below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
What has changed about e.g Cade after using owlrl?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# print without reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# # Print with reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1346</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1346"/>
		<updated>2020-04-19T11:05:08Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, ex.grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
e.g below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# print without reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# # Print with reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1345</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1345"/>
		<updated>2020-04-19T11:03:02Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Populate the ontology with data. E.g like: &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Cade, RDF.type, ex.Graduate))&lt;br /&gt;
g.add((ex.Cade, grade, ex.A))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use owlrl like we did in lab 8 to infer additional triples.&lt;br /&gt;
e.g below I print the ontology before and after the reasoning.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# print without reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl1.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Infer additional triples&lt;br /&gt;
owl_reasoner = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)&lt;br /&gt;
owl_reasoner.closure()&lt;br /&gt;
owl_reasoner.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
# # Print with reasoning&lt;br /&gt;
g.serialize(destination=&amp;quot;owl2.ttl&amp;quot;, format=&amp;quot;turtle&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1344</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1344"/>
		<updated>2020-04-19T10:49:18Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
Use owlrl like we did in lab 8&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1343</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1343"/>
		<updated>2020-04-19T10:45:46Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions and complex classes from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
When solving the tasks look at the notes, find the relevant OWL term/s, and try to use the same principles in python code.&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1342</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1342"/>
		<updated>2020-04-19T10:41:53Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1341</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1341"/>
		<updated>2020-04-19T10:41:34Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
&lt;br /&gt;
Down below is an example solution of the first task: &amp;quot;anyone who is a graduate has at least one degree&amp;quot;.&lt;br /&gt;
It looks complicated, but once you understand it, the other tasks follow a similar pattern. &lt;br /&gt;
In short: I create a blank node that is an OWL.restriction on the ex.degree property.&lt;br /&gt;
The restriction in question is a minCardinaality restriction with the value 1. (e.g &amp;quot;at least one&amp;quot;) &lt;br /&gt;
Then I create another blank node that is for a List of all the criteria that makes a person a Graduate.&lt;br /&gt;
In this case I say that a Graduate is the intersection of a Person and the restriction we creater earlier.&lt;br /&gt;
Collection is essentially used to create lists and everything between [] is what is in the list (the intersections).  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
# anyone who is a graduate has at least one degree&lt;br /&gt;
 &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;
&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;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1340</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1340"/>
		<updated>2020-04-19T10:33:01Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you will mostly use the following OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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.minCaridinality, 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;
&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;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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.minCaridinality, 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1339</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1339"/>
		<updated>2020-04-19T10:32:11Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you may also use the follwing OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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.minCaridinality, 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;
&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;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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.minCaridinality, 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1338</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1338"/>
		<updated>2020-04-19T10:31:32Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these OWL concepts:&lt;br /&gt;
* (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* (SymmetricProperty, TransitiveProperty, InverseFunctionalProperty),&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this lab you may also use the follwing OWL terms:&lt;br /&gt;
&lt;br /&gt;
* (oneOf, unionOf, intersectionOf. complementOf)&lt;br /&gt;
* (Restriction, onProperty)&lt;br /&gt;
* (someValuesFrom, allValuesFrom, hasValue)&lt;br /&gt;
* (cardinality, minCardinality, maxCardinality)&lt;br /&gt;
* (qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=OWL Restrictions=&lt;br /&gt;
Most of the tasks today involve restrictions. &lt;br /&gt;
&lt;br /&gt;
I Recommend refreshing your memories on restrictions from the [https://wiki.uib.no/info216/images/4/48/S11-OWL-15-utlagt.pdf lecture notes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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.minCaridinality, 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;
&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;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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.minCaridinality, 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1337</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1337"/>
		<updated>2020-04-19T10:23:02Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 13: More OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
OWL ontology programming with RDFlib.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these classes and methods:&lt;br /&gt;
* ModelFactory (createOntologyModel),&lt;br /&gt;
* Model (createList, write),&lt;br /&gt;
* OWL (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* OntModel (createClass, createIndividual, createObjectProperty, CreateDatatypeProperty, createAllDifferent, createSymmetricProperty, createTransitiveProperty, createInverseFunctionalProperty),&lt;br /&gt;
* OntClass, Individual, DatatypeProperty, and ObjectProperty.&lt;br /&gt;
&lt;br /&gt;
In this lab you may also use the following ones:&lt;br /&gt;
* OntModel (createAllValuesFromRestriction, create(Min/Max)CardinalityQRestriction, create(Min/Max)CardinalityRestriction, createEnumeratedClass, createHasValueRestriction, createInverseFunctionalProperty, createSomeValuesFromRestriction, createUnionClass)&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
Create or Extend a previous graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above statements as python code using RDFlib and OWL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
&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&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.minCaridinality, 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;
# Continue here with the other statements:&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;turtle&amp;quot;).decode())&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;
In earlier labs we have modeled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1336</id>
		<title>Lab: More OWL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_More_OWL&amp;diff=1336"/>
		<updated>2020-04-19T10:18:11Z</updated>

		<summary type="html">&lt;p&gt;Say004: Created page with &amp;quot; =Lab 9: OWL=  ==Topics== Draw OWL graphs on paper. Basic OWL ontology programming in Jena.  ==Tutorial== https://jena.apache.org/documentation/ontology/  ==Classes and method...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 9: OWL=&lt;br /&gt;
&lt;br /&gt;
==Topics==&lt;br /&gt;
Draw OWL graphs on paper.&lt;br /&gt;
Basic OWL ontology programming in Jena.&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
https://jena.apache.org/documentation/ontology/&lt;br /&gt;
&lt;br /&gt;
==Classes and methods==&lt;br /&gt;
In Lab 8 you have already used these classes and methods:&lt;br /&gt;
* ModelFactory (createOntologyModel),&lt;br /&gt;
* Model (createList, write),&lt;br /&gt;
* OWL (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* OntModel (createClass, createIndividual, createObjectProperty, CreateDatatypeProperty, createAllDifferent, createSymmetricProperty, createTransitiveProperty, createInverseFunctionalProperty),&lt;br /&gt;
* OntClass, Individual, DatatypeProperty, and ObjectProperty.&lt;br /&gt;
&lt;br /&gt;
In this lab you may also use the following ones:&lt;br /&gt;
* OntModel (createAllValuesFromRestriction, create(Min/Max)CardinalityQRestriction, create(Min/Max)CardinalityRestriction, createEnumeratedClass, createHasValueRestriction, createInverseFunctionalProperty, createSomeValuesFromRestriction, createUnionClass)&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
In labs 2, 3 and 8 you have modelled and programmed a scenario. You will find the descriptions at the end of this text.&lt;br /&gt;
&lt;br /&gt;
Extend your graph into an ontology that expresses the following using concepts from OWL (and some from RDF/RDFS):&lt;br /&gt;
* anyone who is a graduate has at least one degree&lt;br /&gt;
* anyone who is a university graduate has at least one degree from a university&lt;br /&gt;
* a grade is either an A, B, C, D, E or F&lt;br /&gt;
* a straight A student is a student that has only A grades&lt;br /&gt;
* a graduate has no F grades&lt;br /&gt;
* a student has a unique student number&lt;br /&gt;
* each student has exactly one average grade&lt;br /&gt;
* a course is either a bachelor, a master or a Ph.D course&lt;br /&gt;
* a bachelor student takes only bachelor courses&lt;br /&gt;
* a masters student takes only master courses and at most one bachelor course&lt;br /&gt;
* a Ph.D student takes only Ph.D and at most two masters courses&lt;br /&gt;
* a Ph.D. student cannot take a bachelor course&lt;br /&gt;
&lt;br /&gt;
Write each of the above staments in Turtle.&lt;br /&gt;
&lt;br /&gt;
Program your ontology in Jena.&lt;br /&gt;
&lt;br /&gt;
==Scenarios from previous labs==&lt;br /&gt;
&lt;br /&gt;
In RDF: &amp;quot;Cade Tracy lives in 1516 Henry Street, Berkeley, California 94709, USA. He has a B.Sc. in biology&lt;br /&gt;
from the University of California, Berkeley from 2011. His interests include birds, ecology, the environment,&lt;br /&gt;
photography and travelling. He has visited Canada and France. Ines Dominguez lives in Carrer de la Guardia&lt;br /&gt;
Civil 20, 46020 Valencia, Spain. She has a M.Sc. in chemistry from the University of Valencia from 2015.&lt;br /&gt;
Her areas of expertise include waste management, toxic waste, air pollution. Her interests include bike&lt;br /&gt;
riding, music and travelling. She has visited Portugal, Italy, France, Germany, Denmark and Sweden. Cade&lt;br /&gt;
knows Ines. They met in Paris in August 2014.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS: &amp;quot;University of California, Berkeley and University of Valencia are both Universities.&lt;br /&gt;
All universities are higher education instituttions (HEIs). Having a B.Sc. from a HEI and having a M.Sc.&lt;br /&gt;
from a HEI are special cases of gradutating from that HEI. That a person has a degree in a subject means&lt;br /&gt;
that the person has expertise in that subject. Only persons can have expertise, and what they have expertise&lt;br /&gt;
about is always a subject.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In RDFS Plus: &amp;quot;Cade and Ines are two different persons. All the countries mentioned above are different. 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). The person class (the RDF type the Cade and Ines resources) 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, http://schema.org/Person, and http://www.aktors.org/ontology/portal#Person, respectively, but on paper you can use prefixes). Nothing can be any two of a person, a university, a city, and a person at the same time. The property you have used in your RDF/RDFS graph to represent that 94709 is the US zip code of Berkeley, California in US is a subproperty of VCard&#039;s postal code-property (http://www.w3.org/2006/vcard/ns#postal-code). No two US cities can have the same postal code. The property you have used for Ines living in Valencia is the same property as FOAF&#039;s based near-property (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). (This is not completely precise: but &amp;quot;hometown&amp;quot; is perhaps the inverse of a subproperty of &amp;quot;based near&amp;quot;.)&lt;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1335</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1335"/>
		<updated>2020-04-17T10:51:32Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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;
===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;
&lt;br /&gt;
==WEB API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1334</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1334"/>
		<updated>2020-04-17T10:46:51Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting - CSV==&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;
==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, 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 + 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;
===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;
&lt;br /&gt;
==WEB API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1333</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1333"/>
		<updated>2020-04-17T10:10:30Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting of CSV==&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;
==WEB API Calls (In this case 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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1332</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=1332"/>
		<updated>2020-04-17T10:09:42Z</updated>

		<summary type="html">&lt;p&gt;Say004: &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;
&lt;br /&gt;
==Lecture 1: Python, RDFlib, and PyCharm==&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;).decode())&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;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: 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 = &amp;quot;https://schema.org/&amp;quot;&lt;br /&gt;
dbp = &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;
&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;
==Lecture 3: SPARQL==&lt;br /&gt;
&lt;br /&gt;
===SPARQL queries from the lecture===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SELECT DISTINCT ?p WHERE {&lt;br /&gt;
    ?s ?p ?o .&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;
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;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
PREFIX owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt;&lt;br /&gt;
CONSTRUCT { &lt;br /&gt;
    ?s owl:sameAs ?o2 . &lt;br /&gt;
} WHERE {&lt;br /&gt;
    ?s owl:sameAs ?o .&lt;br /&gt;
    FILTER(REGEX(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;s&amp;quot;))&lt;br /&gt;
    BIND(URI(REPLACE(STR(?o), &amp;quot;^http://www\\.&amp;quot;, &amp;quot;http://&amp;quot;, &amp;quot;s&amp;quot;)) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&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;
==Lecture 4- SPARQL PROGRAMMING==&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lecture 5: RDFS==&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. Download it [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 started:&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;
# 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;
&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;
===Languaged 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;
== Lecture 6: RDFS Plus / OWL == &lt;br /&gt;
===RDFS Plus / OWL 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;
== Lab 9 ==&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;
==Semantic Lifting of CSV==&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;
==WEB API Calls (In this case JSON)==&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;
&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1331</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=1331"/>
		<updated>2020-04-17T09:13:20Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1330</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=1330"/>
		<updated>2020-04-17T09:02:29Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1329</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=1329"/>
		<updated>2020-04-17T08:54:50Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You can register here if you want to: https://www.geonames.org/login. &lt;br /&gt;
You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1328</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=1328"/>
		<updated>2020-04-17T08:54:26Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). You also need to enable the webservice here: https://www.geonames.org/manageaccount.&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1327</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=1327"/>
		<updated>2020-04-17T08:06:22Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). &#039;&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs (context_data). This data has to eventually be added to out JSON data, with &amp;quot;@context&amp;quot; as the key and context_data as the value. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1326</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=1326"/>
		<updated>2020-04-17T07:54:09Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
@context: signifies a JSON object that contains the&lt;br /&gt;
context (or semantic mapping) for the other objects in&lt;br /&gt;
the same JSON array. (Similar to namespaces)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). &#039;&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs. Put a single entry into this map, with &amp;quot;@context&amp;quot; as the key and another object ({}) as the value. It is this second map that contains the actual mappings. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1325</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=1325"/>
		<updated>2020-04-17T07:53:11Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). &#039;&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) that will contain the context key-value pairs. Put a single entry into this map, with &amp;quot;@context&amp;quot; as the key and another object ({}) as the value. It is this second map that contains the actual mappings. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1324</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=1324"/>
		<updated>2020-04-17T07:41:49Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). &#039;&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) called context. Put a single entry into this map, with &amp;quot;@context&amp;quot; as the key and another object ({}) as the value. It is this second map that contains the actual mappings. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=1323</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=1323"/>
		<updated>2020-04-17T07:41:39Z</updated>

		<summary type="html">&lt;p&gt;Say004: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
=Lab 12: Accessing and lifting Web APIs (RESTful web services)=&lt;br /&gt;
&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) as well as semantic Web APIs (RESTful web services) with JSON and JSON-LD.&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). &lt;br /&gt;
Finally we will parse it with RDFlib. &lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import requests&lt;br /&gt;
* import json&lt;br /&gt;
* import pprint&lt;br /&gt;
* from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Regular JSON web APIs===&lt;br /&gt;
Write a small program that accesses a regular (non-semantic) web API and download the result. The &amp;quot;json&amp;quot; library in python can be used to load a json string as a json object (json.loads(data)).&lt;br /&gt;
Use the the prettyprint import to print a readable version of the json object.&lt;br /&gt;
&lt;br /&gt;
The GeoNames web API (http://www.geonames.org/export/ws-overview.html) offers many services. For example, you can use this URL to access more information about Ines&#039; neighbourhood in Valencia: http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&amp;amp;country=ES&amp;amp;username=demo (You might need to register a username instead of using &amp;quot;demo&amp;quot;). &#039;&lt;br /&gt;
You can register here if you want to: https://www.geonames.org/login&lt;br /&gt;
&lt;br /&gt;
You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: http://opendata.app.uib.no/ , http://data.ssb.no/api , http://ws.audioscrobbler.com/2.0/ , http://www.last.fm/api /intro , http://wiki.musicbrainz.org/Development/JSON_Web_Service .&lt;br /&gt;
&lt;br /&gt;
While you are testing and debugging things, it is good to make measures so that you do not need to call the GeoNames or other API over and over. A solution can be writing the returned data to a file, or copying it into a variable. &lt;br /&gt;
&lt;br /&gt;
Here is an example of a results string you can use, if you have trouble connecting to GeoNames (note that you have to escape all the quotation marks inside the Java string):&lt;br /&gt;
{\&amp;quot;postalcodes\&amp;quot;:[{\&amp;quot;adminCode2\&amp;quot;:\&amp;quot;V\&amp;quot;,\&amp;quot;adminCode1\&amp;quot;:\&amp;quot;VC\&amp;quot;,\&amp;quot;adminName2\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lng\&amp;quot;:-0.377386808395386,\&amp;quot;countryCode\&amp;quot;:\&amp;quot;ES\&amp;quot;,\&amp;quot;postalcode\&amp;quot;:\&amp;quot;46020\&amp;quot;,\&amp;quot;adminName1\&amp;quot;:\&amp;quot;Comunidad Valenciana\&amp;quot;,\&amp;quot;placeName\&amp;quot;:\&amp;quot;Valencia\&amp;quot;,\&amp;quot;lat\&amp;quot;:39.4697524227712}]}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Lifting JSON to JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).&lt;br /&gt;
&lt;br /&gt;
So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) called context. Put a single entry into this map, with &amp;quot;@context&amp;quot; as the key and another object ({}) as the value. It is this second map that contains the actual mappings. &lt;br /&gt;
&lt;br /&gt;
Put at least one pair of strings into it. For example, if you used the postcode API, the pair &amp;quot;lat&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#lat&amp;quot;. You can also put the pair &amp;quot;lng&amp;quot; and &amp;quot;http://www.w3.org/2003/01/geo/wgs84_pos#long&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Add this pair too to the context object: &amp;quot;postalcodes&amp;quot; and &amp;quot;http://dbpedia.org/ontology/postalCode&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
Add more string pairs, using existing or inventing new terms as you go along, to the context object.&lt;br /&gt;
&lt;br /&gt;
Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will now make a RDFlib Graph from the JSON-LD object.&lt;br /&gt;
&lt;br /&gt;
First 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;
Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize(&amp;quot;json-ld&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
===If You have more time===&lt;br /&gt;
&lt;br /&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;/div&gt;</summary>
		<author><name>Say004</name></author>
	</entry>
</feed>