Replacing Multiple String Occurrences with Dictionary Values
In a programming scenario, you may encounter the need to replace multiple occurrences of specific words or phrases within a string using a provided dictionary.
Let's consider an example:
<code class="python">d = { 'Спорт':'Досуг', 'russianA':'englishA' } s = 'Спорт russianA'</code>
The task is to replace each appearance of a key from the dictionary 'd' in the string 's' with the corresponding dictionary value. The expected result for this example is 'Досуг englishA'.
Solution Using Regular Expressions
Utilizing Python's built-in regular expression module 're', we can achieve this replacement efficiently:
<code class="python">import re s = 'Спорт not russianA' d = { 'Спорт':'Досуг', 'russianA':'englishA' } # Escape special characters in dictionary keys keys = (re.escape(k) for k in d.keys()) # Construct a regex pattern with alternating ключей pattern = re.compile(r'\b(' + '|'.join(keys) + r')\b') # Perform substitutions using the provided dictionary result = pattern.sub(lambda x: d[x.group()], s)</code>
This approach uses the 're.sub' method to substitute matches with values from the dictionary 'd'. By using an escaped 'boundary' metacharacter ('b'), we ensure that only whole words are matched.
Extension for Partial Matches
If your dictionary contains some words as substrings of others, sorting the keys descending by length (largest to smallest) before generating the regex pattern is recommended. This prevents substrings from being matched instead of larger words.
The above is the detailed content of How to Replace Multiple String Occurrences Using a Dictionary?. For more information, please follow other related articles on the PHP Chinese website!