Last change
on this file since 2612 was
1927,
checked in by ole, 19 years ago
|
Improved expression parser for apply_expression_to_dictionary()
|
File size:
1.1 KB
|
Line | |
---|
1 | |
---|
2 | def 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 | |
---|
21 | def merge_dictionaries(D1,D2): |
---|
22 | """merge_dictionaries(D1,D2) |
---|
23 | |
---|
24 | Merge two disjoint dictionaries |
---|
25 | The first argument D1 is modified to hold the result of the merger. |
---|
26 | If dictionaries are not disjoint an exception is raised |
---|
27 | """ |
---|
28 | import types |
---|
29 | |
---|
30 | for k in D2.keys(): |
---|
31 | val = D2[k] |
---|
32 | if not D1.has_key(k): |
---|
33 | D1[k] = val |
---|
34 | else: |
---|
35 | print 'Dictionaries not disjoint' |
---|
36 | raise Exception |
---|
37 | |
---|
38 | return D1 |
---|
39 | |
---|
40 | |
---|
41 | |
---|
Note: See
TracBrowser
for help on using the repository browser.