Skip to content

Instantly share code, notes, and snippets.

@NaelsonDouglas
Last active April 10, 2022 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaelsonDouglas/713151d096cd61f1e29478a25aa64a40 to your computer and use it in GitHub Desktop.
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.
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