#!/usr/bin/env python import empty rep = lambda s, i, c: s[ : i ] + c + s[ i + 1 : ] def enc(s, lst): lst = list( filter( lambda c2: c2[ 0 ] in s, lst ) ) e = empty.new() e.s = s def cvt(c2): (c_s, c_d) = c2 ps = [] while c_s in e.s: i = e.s.index( c_s ) e.s = rep( e.s, i, c_d ) ps.append( i ) ps = '_'.join( map( str, ps ) ) return '/'.join( [ 's', c_d, str( ord( c_s ) ), ps ] ) h = '/'.join( map( cvt, reversed( lst ) ) ) return h + ' ' + e.s def dec(s): if ' ' not in s: return s def get_hs(s): i = s.index( ' ' ) (h, s) = ( s[ : i ], s[ i + 1 : ] ) if '/' not in h: return None h = h.split( '/' ) if len( h ) % 4 != 0: return None return empty.new( h=h, s=s ) e = get_hs( s ) if not e: return s def cvt(cmd, c_d, c_s, ps): if cmd != 's': return False c_s = chr( int( c_s ) ) ps = list( map( int, ps.split( '_' ) ) ) for i in ps: if e.s[ i ] != c_d: return False e.s = rep( e.s, i, c_s ) return True while e.h: (h4, e.h) = ( e.h[ : 4 ], e.h[ 4 : ] ) if not cvt( * h4 ): return s return e.s def sample(): s = 'abc.FOO.xyz/KONDOH_bar' lst = [ 'b.', 'O_' ] s_e = enc( s, lst ) s_d = dec( s_e ) print( s ) print( s_e ) print( s_d ) if __name__ == "__main__": sample() # EOF