<s> """<STR_LIT>""" <EOL> import codecs <EOL> import csv <EOL> from rdflib import Variable , BNode , URIRef , Literal , py3compat <EOL> from rdflib . query import Result , ResultSerializer , ResultParser <EOL> class CSVResultParser ( ResultParser ) : <EOL> def __init__ ( self ) : <EOL> self . delim = "<STR_LIT:U+002C>" <EOL> def parse ( self , source ) : <EOL> r = Result ( '<STR_LIT>' ) <EOL> if isinstance ( source . read ( <NUM_LIT:0> ) , py3compat . bytestype ) : <EOL> source = codecs . getreader ( '<STR_LIT:utf-8>' ) ( source ) <EOL> reader = csv . reader ( source , delimiter = self . delim ) <EOL> r . vars = [ Variable ( x ) for x in reader . next ( ) ] <EOL> r . bindings = [ ] <EOL> for row in reader : <EOL> r . bindings . append ( self . parseRow ( row , r . vars ) ) <EOL> return r <EOL> def parseRow ( self , row , v ) : <EOL> return dict ( ( var , val ) <EOL> for var , val in zip ( v , [ self . convertTerm ( t ) <EOL> for t in row ] ) if val is not None ) <EOL> def convertTerm ( self , t ) : <EOL> if t == "<STR_LIT>" : <EOL> return None <EOL> if t . startswith ( "<STR_LIT>" ) : <EOL> return BNode ( t ) <EOL> if t . startswith ( "<STR_LIT>" ) or t . startswith ( "<STR_LIT>" ) : <EOL> return URIRef ( t ) <EOL> return Literal ( t ) <EOL> class CSVResultSerializer ( ResultSerializer ) : <EOL> def __init__ ( self , result ) : <EOL> ResultSerializer . __init__ ( self , result ) <EOL> self . delim = "<STR_LIT:U+002C>" <EOL> if result . type != "<STR_LIT>" : <EOL> raise Exception ( <EOL> "<STR_LIT>" ) <EOL> def serialize ( self , stream , encoding = '<STR_LIT:utf-8>' ) : <EOL> if py3compat . PY3 : <EOL> import codecs <EOL> stream = codecs . getwriter ( encoding ) ( stream ) <EOL> out = csv . writer ( stream , delimiter = self . delim ) <EOL> vs = [ self . serializeTerm ( v , encoding ) for v in self . result . vars ] <EOL> out . writerow ( vs ) <EOL> for row in self . result . bindings : <EOL> out . writerow ( [ self . serializeTerm ( <EOL> row . get ( v ) , encoding ) for v in self . result . vars ] ) <EOL> def serializeTerm ( self , term , encoding ) : <EOL> if term is None : <EOL> return "<STR_LIT>" <EOL> if not py3compat . PY3 : <EOL> return term . encode ( encoding ) <EOL> else : <EOL> return term </s>
