"""RDFSink to TRAMP Conversion Code""" __author__ = "Aaron Swartz" __version__ = 1.0 __license__ = "GNU General Public License Version 2" import sys; sys.path.append('/Users/aaronsw/Projects/cwm/swap/') import RDFSink import rdfapi as rdf class Kitchen(RDFSink.RDFSink): """Class to translate between RDFSink and TRAMP.""" def __init__(self, store=None): if store is None: store = rdf.Store() self.store = store self.bNodes = {} def n(self, node): """Turns an RDFSink carrot into a TRAMP node.""" if node[0] == RDFSink.LITERAL: return rdf.node(unicode(node[1])) if node[0] == RDFSink.ANONYMOUS: if node[1] not in self.bNodes.keys(): self.bNodes[node[1]] = rdf.node() return self.bNodes[node[1]] if node[0] == RDFSink.SYMBOL: if node[1] in self.bNodes.keys(): return self.bNodes[node[1]] else: return rdf.node(str(node[1])) def startDoc(self): pass def endDoc(self): pass def bind(self, pfx, val): pass def makeComment(self, str): pass def makeStatement(self, (scp, pred, subj, obj)): # @@ need to deal with scp if pred[1] == 'http://www.w3.org/2000/10/swap/log#forSome': if obj[1] not in self.bNodes.keys(): self.bNodes[obj[1]] = rdf.node() else: self.store.triple(self.n(subj), self.n(pred), self.n(obj)) def parseN3(text, baseURI, store=None): """Takes an N3 string and returns an RDF store.""" import rdfn3_yapps sink = Kitchen(store) p = rdfn3_yapps.Parser(rdfn3_yapps.scanner(text), sink, baseURI) p.document() return sink.store def parseXMLRDF(text, baseURI, store=None): """Takes a string of XML/RDF and returns an RDF store.""" import xml2rdf sink = Kitchen(store) p = xml2rdf.RDFXMLParser(sink, baseURI) p.feed(text) p.close() return sink.store if __name__ == "__main__": import sys, ntriples text = open(sys.argv[2]).read() baseURI = 'file://localhost'+sys.argv[2] if sys.argv[1] == "--n3": store = parseN3(text, baseURI) elif sys.argv[1] == "--xmlrdf": store = parseXMLRDF(text, baseURI) print ntriples.serialize(store)