July 25, 2003
Parsing RDF with python
I posted my article Some RDF examples and then I asked the RDF crowd in #rdfig to chime in with some comments. They pointed out a syntax error or two. But even better, Dan Connolly took the example and whipped up a quick snippet of code that reads it. He posted it into my comment section but I've cleaned up the formatting a bit and posted it again here. Firstly, make sure you've got python and the rdflib installed and running. Once that's done, put this snippet into a file named foafwk.py:
# cribbed from
# http://rdflib.net/stable/example.py
from rdflib.TripleStore import TripleStore
from rdflib.constants import TYPE
from rdflib.Namespace import Namespace
from rdflib.Literal import Literal
FOAF = Namespace("http://xmlns.com/foaf/0.1/")
EX = Namespace("http://example.org/foovocab#")
def main():
s = TripleStore()
s.load(",ex2.rdf")
# find a guy named bob...
for who in s.subjects(FOAF["name"], Literal("Bob")):
bob = who
# who is secretlyStalking bob?
for who in s.subjects(EX["secretlyStalking"], bob):
for n in s.objects(who, FOAF["name"]):
print n, "is secretlyStalking Bob!"
if __name__ == '__main__':
main()
Then go take third example RDF and paste it into a file named ex2.rdf
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:eg="http://example.org/foovocab#" xmlns:foaf="http://xmlns.com/foaf/0.1/"> <foaf:Person rdf:nodeID="alice"> <foaf:name>Alice</foaf:name> <foaf:knows rdf:nodeID="bob"/> <foaf:knows rdf:nodeID="ted"/> <eg:acquaintance rdf:nodeID="bob"/> <eg:acquaintance rdf:nodeID="ted"/> <eg:archNemesis rdf:nodeID="bob"/> <eg:archNemesis rdf:nodeID="ted"/> </foaf:Person> <foaf:Person rdf:nodeID="bob"> <foaf:knows rdf:nodeID="alice"/> <foaf:knows rdf:nodeID="ted"/> <foaf:name>Bob</foaf:name> <eg:secretlyStalking rdf:nodeID="alice"/> <eg:acquaintance rdf:nodeID="alice"/> <eg:archNemesis rdf:nodeID="ted"/> </foaf:Person> <foaf:Person rdf:nodeID="carol"> <foaf:name>Carol</foaf:name> <foaf:knows rdf:nodeID="alice"/> <foaf:knows rdf:nodeID="ted"/> <eg:secretlyStalking rdf:nodeID="bob"/> <eg:acquaintance rdf:nodeID="alice"/> <eg:acquaintance rdf:nodeID="ted"/> </foaf:Person> <foaf:Person rdf:nodeID="ted"> <foaf:name>Ted</foaf:name> <eg:acquaintance rdf:nodeID="carol"/> <eg:acquaintance rdf:nodeID="alice"/> <eg:archNemesis rdf:nodeID="bob"/> </foaf:Person> </rdf:RDF>Now execute the program:
$ python foafwk.py ,ex2.rdf Carol is secretlyStalking Bob!You can fiddle around with the ex2.rdf file and the python example to learn what more can be done.
Comments







