python - Generate all possible replacements -


given replacement map {search: replace, search: replace, ...} , string, how generate list of possible replacements of string (first substring replaced, second substring replaced, both replaced etc). example:

map = {     'bee': 'beta',     'zee': 'zeta',     'dee': 'delta' }  source_string = 'bee foo zee bar bee'  desired result =  [     'bee foo zee bar bee',      'beta foo zee bar bee',      'bee foo zeta bar bee',      'beta foo zeta bar bee',      'bee foo zee bar beta',      'beta foo zee bar beta',      'bee foo zeta bar beta',      'beta foo zeta bar beta' ] 

the order not important.

'bee foo zee bar bee' => ['bee', 'foo', 'zee', 'bar', 'bee']:

from itertools import product  repl = {     'bee': 'beta',     'zee': 'zeta',     'dee': 'delta' } source_string = 'bee foo zee bar bee' p = product(*((x, repl[x]) if x in repl else (x,) x in source_string.split())) x in p:     print(x) 

output:

('bee', 'foo', 'zee', 'bar', 'bee') ('bee', 'foo', 'zee', 'bar', 'beta') ('bee', 'foo', 'zeta', 'bar', 'bee') ('bee', 'foo', 'zeta', 'bar', 'beta') ('beta', 'foo', 'zee', 'bar', 'bee') ('beta', 'foo', 'zee', 'bar', 'beta') ('beta', 'foo', 'zeta', 'bar', 'bee') ('beta', 'foo', 'zeta', 'bar', 'beta') 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -