home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / rdflib / syntax / parsers / ntriples.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  9.6 KB  |  297 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. N-Triples Parser
  6. License: GPL 2, W3C, BSD, or MIT
  7. Author: Sean B. Palmer, inamidst.com
  8. Documentation:
  9.    http://inamidst.com/proj/rdf/ntriples-doc
  10.  
  11. Command line usage:
  12.    ./ntriples.py <URI>    - parses URI as N-Triples
  13.    ./ntriples.py --help   - prints out this help message
  14. # @@ fully empty document?
  15. '''
  16. import re
  17. uriref = '<([^:]+:[^\\s"<>]+)>'
  18. literal = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'
  19. litinfo = '(?:@([a-z]+(?:-[a-z0-9]+)*)|\\^\\^' + uriref + ')?'
  20. r_line = re.compile('([^\\r\\n]*)(?:\\r\\n|\\r|\\n)')
  21. r_wspace = re.compile('[ \\t]*')
  22. r_wspaces = re.compile('[ \\t]+')
  23. r_tail = re.compile('[ \\t]*\\.[ \\t]*')
  24. r_uriref = re.compile(uriref)
  25. r_nodeid = re.compile('_:([A-Za-z][A-Za-z0-9]*)')
  26. r_literal = re.compile(literal + litinfo)
  27. bufsiz = 2048
  28. validate = False
  29.  
  30. class Node(unicode):
  31.     pass
  32.  
  33. from rdflib import URIRef as URI
  34. from rdflib import BNode as bNode
  35. from rdflib import Literal
  36.  
  37. class Sink(object):
  38.     
  39.     def __init__(self):
  40.         self.length = 0
  41.  
  42.     
  43.     def triple(self, s, p, o):
  44.         self.length += 1
  45.         print (s, p, o)
  46.  
  47.  
  48.  
  49. class ParseError(Exception):
  50.     pass
  51.  
  52. quot = {
  53.     't': '\t',
  54.     'n': '\n',
  55.     'r': '\r',
  56.     '"': '"',
  57.     '\\': '\\' }
  58. r_safe = re.compile('([\\x20\\x21\\x23-\\x5B\\x5D-\\x7E]+)')
  59. r_quot = re.compile('\\\\(t|n|r|"|\\\\)')
  60. r_uniquot = re.compile('\\\\u([0-9A-F]{4})|\\\\U([0-9A-F]{8})')
  61.  
  62. def unquote(s):
  63.     '''Unquote an N-Triples string.'''
  64.     result = []
  65.     while s:
  66.         m = r_safe.match(s)
  67.         if m:
  68.             s = s[m.end():]
  69.             result.append(m.group(1))
  70.             continue
  71.         
  72.         m = r_quot.match(s)
  73.         if m:
  74.             s = s[2:]
  75.             result.append(quot[m.group(1)])
  76.             continue
  77.         
  78.         m = r_uniquot.match(s)
  79.         if m:
  80.             s = s[m.end():]
  81.             (u, U) = m.groups()
  82.             if not u:
  83.                 pass
  84.             codepoint = int(U, 16)
  85.             if codepoint > 1114111:
  86.                 raise ParseError('Disallowed codepoint: %08X' % codepoint)
  87.             codepoint > 1114111
  88.             result.append(unichr(codepoint))
  89.             continue
  90.         if s.startswith('\\'):
  91.             raise ParseError('Illegal escape at: %s...' % s[:10])
  92.         s.startswith('\\')
  93.         raise ParseError('Illegal literal character: %r' % s[0])
  94.     return unicode(''.join(result))
  95.  
  96. if not validate:
  97.     
  98.     def unquote(s):
  99.         return s.decode('unicode-escape')
  100.  
  101.  
  102. r_hibyte = re.compile('([\\x80-\\xFF])')
  103.  
  104. def uriquote(uri):
  105.     return r_hibyte.sub((lambda m: '%%%02X' % ord(m.group(1))), uri)
  106.  
  107. if not validate:
  108.     
  109.     def uriquote(uri):
  110.         return uri
  111.  
  112.  
  113.  
  114. class NTriplesParser(object):
  115.     '''An N-Triples Parser.
  116.       Usage:
  117.          p = NTriplesParser(sink=MySink())
  118.          sink = p.parse(f) # file; use parsestring for a string
  119.    '''
  120.     
  121.     def __init__(self, sink = None):
  122.         if sink is not None:
  123.             self.sink = sink
  124.         else:
  125.             self.sink = Sink()
  126.  
  127.     
  128.     def parse(self, f):
  129.         '''Parse f as an N-Triples file.'''
  130.         if not hasattr(f, 'read'):
  131.             raise ParseError('Item to parse must be a file-like object.')
  132.         hasattr(f, 'read')
  133.         self.file = f
  134.         self.buffer = ''
  135.         while True:
  136.             self.line = self.readline()
  137.             if self.line is None:
  138.                 break
  139.             
  140.             
  141.             try:
  142.                 self.parseline()
  143.             continue
  144.             except ParseError:
  145.                 raise ParseError('Invalid line: %r' % self.line)
  146.                 continue
  147.             
  148.  
  149.             None<EXCEPTION MATCH>ParseError
  150.         return self.sink
  151.  
  152.     
  153.     def parsestring(self, s):
  154.         '''Parse s as an N-Triples string.'''
  155.         if not isinstance(s, basestring):
  156.             raise ParseError('Item to parse must be a string instance.')
  157.         isinstance(s, basestring)
  158.         StringIO = StringIO
  159.         import cStringIO
  160.         f = StringIO()
  161.         f.write(s)
  162.         f.seek(0)
  163.         self.parse(f)
  164.  
  165.     
  166.     def readline(self):
  167.         '''Read an N-Triples line from buffered input.'''
  168.         if not self.buffer:
  169.             buffer = self.file.read(bufsiz)
  170.             if not buffer:
  171.                 return None
  172.             self.buffer = buffer
  173.         
  174.         while True:
  175.             m = r_line.match(self.buffer)
  176.             if m:
  177.                 self.buffer = self.buffer[m.end():]
  178.                 return m.group(1)
  179.             buffer = self.file.read(bufsiz)
  180.             if not buffer:
  181.                 raise ParseError('EOF in line')
  182.             buffer
  183.             self.buffer += buffer
  184.             continue
  185.             self
  186.  
  187.     
  188.     def parseline(self):
  189.         self.eat(r_wspace)
  190.         if not (self.line) or self.line.startswith('#'):
  191.             return None
  192.         subject = self.subject()
  193.         self.eat(r_wspaces)
  194.         predicate = self.predicate()
  195.         self.eat(r_wspaces)
  196.         object = self.object()
  197.         self.eat(r_tail)
  198.         if self.line:
  199.             raise ParseError('Trailing garbage')
  200.         self.line
  201.         self.sink.triple(subject, predicate, object)
  202.  
  203.     
  204.     def peek(self, token):
  205.         return self.line.startswith(token)
  206.  
  207.     
  208.     def eat(self, pattern):
  209.         m = pattern.match(self.line)
  210.         if not m:
  211.             raise ParseError('Failed to eat %s' % pattern)
  212.         m
  213.         self.line = self.line[m.end():]
  214.         return m
  215.  
  216.     
  217.     def subject(self):
  218.         if not self.uriref():
  219.             pass
  220.         subj = self.nodeid()
  221.         if not subj:
  222.             raise ParseError('Subject must be uriref or nodeID')
  223.         subj
  224.         return subj
  225.  
  226.     
  227.     def predicate(self):
  228.         pred = self.uriref()
  229.         if not pred:
  230.             raise ParseError('Predicate must be uriref')
  231.         pred
  232.         return pred
  233.  
  234.     
  235.     def object(self):
  236.         if not self.uriref() and self.nodeid():
  237.             pass
  238.         objt = self.literal()
  239.         if objt is False:
  240.             raise ParseError('Unrecognised object type')
  241.         objt is False
  242.         return objt
  243.  
  244.     
  245.     def uriref(self):
  246.         if self.peek('<'):
  247.             uri = self.eat(r_uriref).group(1)
  248.             uri = unquote(uri)
  249.             uri = uriquote(uri)
  250.             return URI(uri)
  251.         return False
  252.  
  253.     
  254.     def nodeid(self):
  255.         if self.peek('_'):
  256.             return bNode(self.eat(r_nodeid).group(1))
  257.         return False
  258.  
  259.     
  260.     def literal(self):
  261.         if self.peek('"'):
  262.             (lit, lang, dtype) = self.eat(r_literal).groups()
  263.             if not lang:
  264.                 pass
  265.             lang = None
  266.             if not dtype:
  267.                 pass
  268.             dtype = None
  269.             if lang and dtype:
  270.                 raise ParseError("Can't have both a language and a datatype")
  271.             dtype
  272.             lit = unquote(lit)
  273.             return Literal(lit, lang, dtype)
  274.         return False
  275.  
  276.  
  277.  
  278. def parseURI(uri):
  279.     import urllib
  280.     parser = NTriplesParser()
  281.     u = urllib.urlopen(uri)
  282.     sink = parser.parse(u)
  283.     u.close()
  284.     print 'Length of input:', sink.length
  285.  
  286.  
  287. def main():
  288.     import sys
  289.     if len(sys.argv) == 2:
  290.         parseURI(sys.argv[1])
  291.     else:
  292.         print __doc__
  293.  
  294. if __name__ == '__main__':
  295.     main()
  296.  
  297.