summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorGunnar Aastrand Grimnes <gromgull@gmail.com>2016-11-19 07:44:22 +0100
committerGunnar Aastrand Grimnes <gromgull@gmail.com>2017-01-30 17:43:04 +0100
commitfbf32e11862ca4d07b745a36b4389e900c60c00d (patch)
treed44c38852bc98fef2a903c56a2ac980ae0385f6f /examples
parentf007dace0a39c242ae450611b18463c774696253 (diff)
downloadrdflib-fbf32e11862ca4d07b745a36b4389e900c60c00d.tar.gz
converted examples
Diffstat (limited to 'examples')
-rw-r--r--examples/conjunctive_graphs.py4
-rw-r--r--examples/custom_datatype.py12
-rw-r--r--examples/custom_eval.py2
-rw-r--r--examples/film.py28
-rw-r--r--examples/foafpaths.py8
-rw-r--r--examples/prepared_query.py6
-rw-r--r--examples/rdfa_example.py10
-rw-r--r--examples/resource.py16
-rw-r--r--examples/simple_example.py29
-rw-r--r--examples/sleepycat_example.py28
-rw-r--r--examples/slice.py7
-rw-r--r--examples/smushing.py2
-rw-r--r--examples/sparql_query_example.py8
-rw-r--r--examples/sparql_update_example.py2
-rw-r--r--examples/sparqlstore_example.py9
-rw-r--r--examples/swap_primer.py12
-rw-r--r--examples/transitive.py9
17 files changed, 89 insertions, 103 deletions
diff --git a/examples/conjunctive_graphs.py b/examples/conjunctive_graphs.py
index 0b7d297e..a5e5a71f 100644
--- a/examples/conjunctive_graphs.py
+++ b/examples/conjunctive_graphs.py
@@ -53,6 +53,6 @@ if __name__=='__main__':
# query the conjunction of all graphs
- print 'Mary loves:'
+ print('Mary loves:')
for x in g[mary : ns.loves/ns.hasName]:
- print x
+ print(x)
diff --git a/examples/custom_datatype.py b/examples/custom_datatype.py
index 01aa5acb..34bde44c 100644
--- a/examples/custom_datatype.py
+++ b/examples/custom_datatype.py
@@ -1,6 +1,6 @@
"""
-RDFLib can map between data-typed literals and python objects.
+RDFLib can map between data-typed literals and python objects.
Mapping for integers, floats, dateTimes, etc. are already added, but
you can also add your own.
@@ -17,9 +17,9 @@ from rdflib.term import bind
if __name__=='__main__':
# complex numbers are not registered by default
- # no custom constructor/serializer needed since
+ # no custom constructor/serializer needed since
# complex('(2+3j)') works fine
- bind(XSD.complexNumber, complex)
+ bind(XSD.complexNumber, complex)
ns=Namespace("urn:my:namespace:")
@@ -39,8 +39,6 @@ if __name__=='__main__':
l2=list(g2)[0][2]
- print l2
-
- print l2.value == c # back to a python complex object
-
+ print(l2)
+ print(l2.value == c) # back to a python complex object
diff --git a/examples/custom_eval.py b/examples/custom_eval.py
index 89975168..bad8ff1c 100644
--- a/examples/custom_eval.py
+++ b/examples/custom_eval.py
@@ -65,4 +65,4 @@ if __name__=='__main__':
# Find all FOAF Agents
for x in g.query(
'PREFIX foaf: <%s> SELECT * WHERE { ?s a foaf:Agent . }' % FOAF):
- print x
+ print(x)
diff --git a/examples/film.py b/examples/film.py
index 832ba3be..b18341e8 100644
--- a/examples/film.py
+++ b/examples/film.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-"""
+"""
film.py: a simple tool to manage your movies review
Simon Rozet, http://atonie.org/
@@ -10,7 +10,7 @@ Simon Rozet, http://atonie.org/
- handle non IMDB uri
- markdown support in comment
-Requires download and import of Python imdb library from
+Requires download and import of Python imdb library from
http://imdbpy.sourceforge.net/ - (warning: installation
will trigger automatic installation of several other packages)
@@ -25,14 +25,14 @@ Usage:
"""
import datetime, os, sys, re, time
-try:
+try:
import imdb
-except ImportError:
+except ImportError:
imdb = None
from rdflib import BNode, ConjunctiveGraph, URIRef, Literal, Namespace, RDF
from rdflib.namespace import FOAF, DC
-
+from rdflib.py3compat import input
storefn = os.path.expanduser('~/movies.n3')
#storefn = '/home/simon/codes/film.dev/movies.n3'
@@ -53,10 +53,10 @@ class Store:
self.graph.bind('foaf', FOAF)
self.graph.bind('imdb', IMDB)
self.graph.bind('rev', 'http://purl.org/stuff/rev#')
-
+
def save(self):
self.graph.serialize(storeuri, format='n3')
-
+
def who(self, who=None):
if who is not None:
name, email = (r_who.match(who).group(1), r_who.match(who).group(2))
@@ -67,14 +67,14 @@ class Store:
self.save()
else:
return self.graph.objects(URIRef(storeuri+'#author'), FOAF['name'])
-
+
def new_movie(self, movie):
movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
self.graph.add((movieuri, RDF.type, IMDB['Movie']))
self.graph.add((movieuri, DC['title'], Literal(movie['title'])))
self.graph.add((movieuri, IMDB['year'], Literal(int(movie['year']))))
self.save()
-
+
def new_review(self, movie, date, rating, comment=None):
review = BNode() # @@ humanize the identifier (something like #rev-$date)
movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
@@ -91,7 +91,7 @@ class Store:
def movie_is_in(self, uri):
return (URIRef(uri), RDF.type, IMDB['Movie']) in self.graph
-
+
def help():
print(__doc__.split('--')[1])
@@ -121,22 +121,22 @@ def main(argv=None):
rating = None
while not rating or (rating > 5 or rating <= 0):
try:
- rating = int(raw_input('Rating (on five): '))
+ rating = int(input('Rating (on five): '))
except ValueError:
rating = None
date = None
while not date:
try:
- i = raw_input('Review date (YYYY-MM-DD): ')
+ i = input('Review date (YYYY-MM-DD): ')
date = datetime.datetime(*time.strptime(i, '%Y-%m-%d')[:6])
except:
date = None
- comment = raw_input('Comment: ')
+ comment = input('Comment: ')
s.new_review(movie, date, rating, comment)
else:
help()
if __name__ == '__main__':
- if not imdb:
+ if not imdb:
raise Exception('This example requires the IMDB library! Install with "pip install imdbpy"')
main()
diff --git a/examples/foafpaths.py b/examples/foafpaths.py
index 81179347..9209500b 100644
--- a/examples/foafpaths.py
+++ b/examples/foafpaths.py
@@ -4,7 +4,7 @@ SPARQL 1.1 defines path operators for combining/repeating predicates
in triple-patterns.
We overload some python operators on URIRefs to allow creating path
-operators directly in python.
+operators directly in python.
============ =========================================
Operator Path
@@ -13,7 +13,7 @@ Operator Path
``p1 | p2`` Path alternative
``p1 * '*'`` chain of 0 or more p's
``p1 * '+'`` chain of 1 or more p's
-``p1 * '?'`` 0 or 1 p
+``p1 * '?'`` 0 or 1 p
``~p1`` p1 inverted, i.e. (s p1 o) <=> (o ~p1 s)
``-p1`` NOT p1, i.e. any property but p1
============ =========================================
@@ -38,7 +38,7 @@ if __name__=='__main__':
tim = URIRef("http://www.w3.org/People/Berners-Lee/card#i")
- print "Timbl knows:"
+ print("Timbl knows:")
for o in g.objects(tim, FOAF.knows / FOAF.name):
- print o
+ print(o)
diff --git a/examples/prepared_query.py b/examples/prepared_query.py
index f67c1b5e..2906783f 100644
--- a/examples/prepared_query.py
+++ b/examples/prepared_query.py
@@ -4,7 +4,7 @@
SPARQL Queries be prepared (i.e parsed and translated to SPARQL algebra)
by the :meth:`rdflib.plugins.sparql.prepareQuery` method.
-When executing, variables can be bound with the
+When executing, variables can be bound with the
``initBindings`` keyword parameter
@@ -17,7 +17,7 @@ from rdflib.namespace import FOAF
if __name__=='__main__':
q = prepareQuery(
- 'SELECT ?s WHERE { ?person foaf:knows ?s .}',
+ 'SELECT ?s WHERE { ?person foaf:knows ?s .}',
initNs = { "foaf": FOAF })
g = rdflib.Graph()
@@ -26,4 +26,4 @@ if __name__=='__main__':
tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i")
for row in g.query(q, initBindings={'person': tim}):
- print row
+ print(row)
diff --git a/examples/rdfa_example.py b/examples/rdfa_example.py
index 02112ce3..000644ec 100644
--- a/examples/rdfa_example.py
+++ b/examples/rdfa_example.py
@@ -1,5 +1,5 @@
"""
-
+
A simple example showing how to process RDFa from the web
"""
@@ -11,12 +11,12 @@ if __name__ == '__main__':
g.parse('http://www.worldcat.org/title/library-of-babel/oclc/44089369', format='rdfa')
- print "Books found:"
+ print("Books found:")
- for row in g.query("""SELECT ?title ?author WHERE {
- [ a schema:Book ;
+ for row in g.query("""SELECT ?title ?author WHERE {
+ [ a schema:Book ;
schema:author [ rdfs:label ?author ] ;
schema:name ?title ]
FILTER (LANG(?title) = 'en') } """):
- print "%s by %s"%(row.title, row.author)
+ print("%s by %s"%(row.title, row.author))
diff --git a/examples/resource.py b/examples/resource.py
index 4a738efd..d254e751 100644
--- a/examples/resource.py
+++ b/examples/resource.py
@@ -32,20 +32,18 @@ if __name__=='__main__':
# Resources returned when querying are 'auto-boxed' as resources:
- print "Bill's friend: ", bill.value(FOAF.knows).value(FOAF.name)
+ print("Bill's friend: ", bill.value(FOAF.knows).value(FOAF.name))
- # slicing ([] syntax) can also be used:
+ # slicing ([] syntax) can also be used:
- print "Bill knows: ",
- for friend in bill[FOAF.knows]:
- print friend[FOAF.name].next(), " "
+ print("Bill knows: ")
+ for friend in bill[FOAF.knows]:
+ print(next(friend[FOAF.name]))
# or even quicker with paths:
- print "Bill knows: ",
+ print("Bill knows: ")
for friend in bill[FOAF.knows/FOAF.name]:
- print friend
+ print(friend)
# setting single properties is also possible:
bill[RDFS.label]=Literal("William")
-
- print g.serialize(format='n3')
diff --git a/examples/simple_example.py b/examples/simple_example.py
index 7b44ff79..5ed4be62 100644
--- a/examples/simple_example.py
+++ b/examples/simple_example.py
@@ -19,35 +19,34 @@ if __name__=='__main__':
store.add((donna, FOAF.name, Literal("Donna Fales")))
# Iterate over triples in store and print them out.
- print "--- printing raw triples ---"
+ print("--- printing raw triples ---")
for s, p, o in store:
- print s, p, o
+ print(s, p, o)
# For each foaf:Person in the store print out its mbox property.
- print "--- printing mboxes ---"
+ print("--- printing mboxes ---")
for person in store.subjects(RDF.type, FOAF["Person"]):
for mbox in store.objects(person, FOAF["mbox"]):
- print mbox
+ print(mbox)
# Serialize the store as RDF/XML to the file donna_foaf.rdf.
store.serialize("donna_foaf.rdf", format="pretty-xml", max_depth=3)
# Let's show off the serializers
- print "RDF Serializations:"
+ print("RDF Serializations:")
# Serialize as XML
- print "--- start: rdf-xml ---"
- print store.serialize(format="pretty-xml")
- print "--- end: rdf-xml ---\n"
+ print("--- start: rdf-xml ---")
+ print(store.serialize(format="pretty-xml"))
+ print("--- end: rdf-xml ---\n")
# Serialize as Turtle
- print "--- start: turtle ---"
- print store.serialize(format="turtle")
- print "--- end: turtle ---\n"
+ print("--- start: turtle ---")
+ print(store.serialize(format="turtle"))
+ print("--- end: turtle ---\n")
# Serialize as NTriples
- print "--- start: ntriples ---"
- print store.serialize(format="nt")
- print "--- end: ntriples ---\n"
-
+ print("--- start: ntriples ---")
+ print(store.serialize(format="nt"))
+ print("--- end: ntriples ---\n")
diff --git a/examples/sleepycat_example.py b/examples/sleepycat_example.py
index 93725fe1..417897fa 100644
--- a/examples/sleepycat_example.py
+++ b/examples/sleepycat_example.py
@@ -15,7 +15,7 @@ if __name__ == '__main__':
# Open previously created store, or create it if it doesn't exist yet
graph = ConjunctiveGraph('Sleepycat')
-
+
rt = graph.open(path, create=False)
if rt == NO_STORE:
@@ -24,7 +24,7 @@ if __name__ == '__main__':
else:
assert rt == VALID_STORE, 'The underlying store is corrupt'
- print 'Triples in graph before add: ', len(graph)
+ print('Triples in graph before add: ', len(graph))
# Now we'll add some triples to the graph & commit the changes
rdflib = Namespace('http://rdflib.net/test/')
@@ -33,28 +33,28 @@ if __name__ == '__main__':
graph.add((rdflib['pic:1'], rdflib.name, Literal('Jane & Bob')))
graph.add((rdflib['pic:2'], rdflib.name, Literal('Squirrel in Tree')))
- print 'Triples in graph after add: ', len(graph)
+ print('Triples in graph after add: ', len(graph))
# display the graph in RDF/XML
- print graph.serialize(format='n3')
+ print(graph.serialize(format='n3'))
- # close when done, otherwise sleepycat will leak lock entries.
+ # close when done, otherwise sleepycat will leak lock entries.
graph.close()
-
+
graph = None
-
+
# reopen the graph
-
+
graph = ConjunctiveGraph('Sleepycat')
-
- graph.open(path, create = False)
-
- print 'Triples still in graph: ', len(graph)
-
+
+ graph.open(path, create = False)
+
+ print('Triples still in graph: ', len(graph))
+
graph.close()
# Clean up the temp folder to remove the Sleepycat database files...
import os
- for f in os.listdir(path):
+ for f in os.listdir(path):
os.unlink(path+'/'+f)
os.rmdir(path)
diff --git a/examples/slice.py b/examples/slice.py
index 2e4e2d8b..e3d21b40 100644
--- a/examples/slice.py
+++ b/examples/slice.py
@@ -23,8 +23,7 @@ if __name__=='__main__':
for person in graph[: RDF.type : FOAF.Person]:
friends = list(graph[person:FOAF.knows * '+'/FOAF.name])
- if friends:
- print "%s's circle of friends:"%graph.value(person, FOAF.name)
+ if friends:
+ print("%s's circle of friends:"%graph.value(person, FOAF.name))
for name in friends:
- print name
-
+ print(name)
diff --git a/examples/smushing.py b/examples/smushing.py
index 6197e1e2..fbd5dd25 100644
--- a/examples/smushing.py
+++ b/examples/smushing.py
@@ -44,4 +44,4 @@ if __name__=='__main__':
o = newURI.get(o, o) # might be linked to another person
out.add((s,p,o))
- print out.serialize(format="n3")
+ print(out.serialize(format="n3").decode('utf-8'))
diff --git a/examples/sparql_query_example.py b/examples/sparql_query_example.py
index 90417b5e..1698c706 100644
--- a/examples/sparql_query_example.py
+++ b/examples/sparql_query_example.py
@@ -4,7 +4,7 @@
SPARQL Query using :meth:`rdflib.graph.Graph.query`
The method returns a :class:`~rdflib.query.Result`, iterating over
-this yields :class:`~rdflib.query.ResultRow` objects
+this yields :class:`~rdflib.query.ResultRow` objects
The variable bindings can be access as attributes of the row objects
For variable names that are not valid python identifiers, dict access
@@ -25,10 +25,6 @@ if __name__=='__main__':
# which in turn knows it from reading the RDF/XML file
for row in g.query(
'select ?s where { [] foaf:knows ?s .}'):
- print row.s
+ print(row.s)
# or row["s"]
# or row[rdflib.Variable("s")]
-
-
-
-
diff --git a/examples/sparql_update_example.py b/examples/sparql_update_example.py
index ece18ed7..99156135 100644
--- a/examples/sparql_update_example.py
+++ b/examples/sparql_update_example.py
@@ -23,4 +23,4 @@ if __name__=='__main__':
for x in g.subjects(
rdflib.RDF.type, rdflib.URIRef('http://dbpedia.org/resource/Human')):
- print x
+ print(x)
diff --git a/examples/sparqlstore_example.py b/examples/sparqlstore_example.py
index e9236110..4f828913 100644
--- a/examples/sparqlstore_example.py
+++ b/examples/sparqlstore_example.py
@@ -6,17 +6,16 @@ A simple example showing how to use the SPARQLStore
from rdflib import Graph, URIRef, Namespace
-if __name__ == '__main__':
+if __name__ == '__main__':
dbo = Namespace('http://dbpedia.org/ontology/')
- graph = Graph('SPARQLStore')
+ graph = Graph('SPARQLStore')
graph.open("http://dbpedia.org/sparql")
pop = graph.value(
- URIRef("http://dbpedia.org/resource/Berlin"),
+ URIRef("http://dbpedia.org/resource/Berlin"),
dbo.populationTotal)
- print "According to DBPedia Berlin has a population of", pop
-
+ print("According to DBPedia Berlin has a population of", pop)
diff --git a/examples/swap_primer.py b/examples/swap_primer.py
index aee57185..e44c34f2 100644
--- a/examples/swap_primer.py
+++ b/examples/swap_primer.py
@@ -1,6 +1,6 @@
"""
-This is a simple primer using some of the
+This is a simple primer using some of the
example stuff in the Primer on N3:
http://www.w3.org/2000/10/swap/Primer
@@ -93,7 +93,7 @@ if __name__=='__main__':
:sister a rdf:Property.
- :sister rdfs:domain :Person;
+ :sister rdfs:domain :Person;
rdfs:range :Woman.
:Woman = foo:FemaleAdult .
@@ -103,10 +103,10 @@ if __name__=='__main__':
""" # --- End of primer code
- # To make this go easier to spit back out...
+ # To make this go easier to spit back out...
# technically, we already created a namespace
# with the object init (and it added some namespaces as well)
- # By default, your main namespace is the URI of your
+ # By default, your main namespace is the URI of your
# current working directory, so lets make that simpler:
myNS = Namespace('http://www.w3.org/2000/10/swap/Primer#')
@@ -126,7 +126,7 @@ if __name__=='__main__':
# or spit it back out (mostly) the way we created it:
- print primer.serialize(format='n3')
+ print(primer.serialize(format='n3'))
# for more insight into things already done, lets see the namespaces
@@ -135,5 +135,3 @@ if __name__=='__main__':
# lets ask something about the data
list(primer.objects(myNS.pat, myNS.child))
-
-
diff --git a/examples/transitive.py b/examples/transitive.py
index dfa503be..dad3a07b 100644
--- a/examples/transitive.py
+++ b/examples/transitive.py
@@ -66,11 +66,10 @@ if __name__=='__main__':
g.add((mom, parent, momOfMom))
g.add((mom, parent, dadOfMom))
- print "Parents, forward from `ex:person`:"
+ print("Parents, forward from `ex:person`:")
for i in g.transitive_objects(person, parent):
- print i
+ print(i)
- print "Parents, *backward* from `ex:gm1`:"
+ print("Parents, *backward* from `ex:gm1`:")
for i in g.transitive_subjects(parent, momOfMom):
- print i
-
+ print(i)