Python idiom: Multiple search-and-replace

Randall Hopper aa8vb at yahoo.com
Wed Apr 12 17:40:01 CEST 2000


Siggy Brentrup:
 |Randall Hopper:
 |> I want to do search-and-replace of multiple symbols on each line of a file.
 |> But the simple-minded code below takes a while.
...
 |> --------------------------------------------------------------------------
 |> 
 |>   symbol_map = { 'oldsym1' : 'newsym1', oldsym2' : 'newsym2', ... }
 |>   fp = open( net_path, "r" )
 |> 
 |>   while 1:
 |>     line = fp.readline()
 |>     if not line: break
 |> 
 |>     for old_sym in symbol_map.keys():
 |>       line = string.replace( line, old_sym, symbol_map[ old_sym ] )
 |> 
 |>     out_fp.write( line )
 |> 
 |> --------------------------------------------------------------------------
 |
 |symbol_items = symbol_map.items()
 |
 |while 1:
 |    line = fp.readline()
 |    if not line: break
 |
 |    for old, new in symbol_items:
 |        line = string.replace(line, old, new)
 |
 |    out_fp.write(line)


Actually I'd tried this.  About the same speed (a few seconds slower).  The
dictionary lookups were not slowing the original algorithm.  But thanks.

-- 
Randall Hopper
aa8vb at yahoo.com




More information about the Python-list mailing list