Last active
April 10, 2022 07:55
-
-
Save NaelsonDouglas/713151d096cd61f1e29478a25aa64a40 to your computer and use it in GitHub Desktop.
This function replaces severall patterns in a single iteration. Just pass the text to be replaced and the mappings dictionary to it. Longer words are replaced first.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def bulk_replace(text:str, mappings:str) -> str: | |
regex = re.compile('|'.join(mappings.keys())) | |
return re.sub(regex, lambda x: mappings[x.group()], text) | |
if __name__ == '__main__': | |
mappings = { | |
'quick':'slow', | |
'fox':'dog', | |
'dog':'fox' | |
} | |
text = 'the quick brown fox jumps over the lazy dog' | |
text = bulk_replace(text, mappings) | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment