python rdflib sample

Need to generate rdf-xml strings:


#!/usr/bin/python
# -*- coding: utf-8 -*-

import rdflib
from rdflib.graph import ConjunctiveGraph
from rdflib import plugin, BNode, Literal, RDF, Namespace

graph = ConjunctiveGraph()
# bind is needed to attach namespaces to xmlns prefixes
graph.bind("foaf", "http://xmlns.com/foaf/0.1/")

# namespace object, used for qualifying subject, object or predicate
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

john = BNode() # subject is BNode
graph.add((john, FOAF['nick'], Literal('john'))) # subject, predicate, object
graph.add((john, FOAF['name'], Literal('John Doe')))
graph.add((john, RDF.type, FOAF['Person'])) # create a resource object

print graph.serialize() # serialize defaults to xml notation


Or as ntriples:


#!/usr/bin/python
# -*- coding: utf-8 -*-

import rdflib
from rdflib.graph import ConjunctiveGraph
from rdflib import plugin, BNode, Literal, RDF, Namespace

graph = ConjunctiveGraph()

dc = Namespace("http://purl.org/dc/elements/1.1/")
graph.bind("dc", "http://purl.org/dc/elements/1.1/")
trite = Namespace("http://owtrsnc.blogspot.com/")
graph.bind("trite", "http://owtrsnc.blogspot.com/")

# the format is -> graph.add( (subject,predicate,object) )
graph.add( (trite["2009/06/doing-rest-with-django-part-1-research.html"], dc['title'], Literal('Doing REST with django, part 1 - research') ) )
graph.add( (trite["2009/06/doing-rest-with-django-part-1-research.html"], dc['creator'], Literal('owtrsnc') ) )

#in ntriples
print graph.serialize()
print graph.serialize(format='nt')

Comments

Popular posts from this blog

Handling control characters (escaping) in python for json and mysql

python port sniffer with pcapy and impacket

Django field, form and model validation process