Changeset 1927 for tools


Ignore:
Timestamp:
Oct 14, 2005, 4:14:19 PM (20 years ago)
Author:
ole
Message:

Improved expression parser for apply_expression_to_dictionary()

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tools/pytools/misc.py

    r18 r1927  
    11     
     2def multiple_replace(dictionary, text):
     3    """Multiple replace
     4
     5    Python Cookbook 3.14 page 88 and page 90
     6    """
     7
     8    import re
     9   
     10    #Create a regular expression from all of the dictionary keys
     11    #matching only entire words
     12    #regex = re.compile("|".join(map(re.escape, dictionary.keys())))
     13    regex = re.compile(r'\b'+ \
     14                       r'\b|\b'.join(map(re.escape, dictionary.keys()))+ \
     15                       r'\b' )
     16
     17    #For each match, lookup the corresponding value in the dictionary
     18    return regex.sub(lambda match: dictionary[match.group(0)], text)
     19
     20
    221def merge_dictionaries(D1,D2):
    322    """merge_dictionaries(D1,D2)
     
    1938    return D1
    2039
     40
     41
Note: See TracChangeset for help on using the changeset viewer.