[Python] I made a function that can also use regular expressions that replace character strings all at once.

Introduction

When replacing a character string with multiple patterns, it tends to be redundant code like ↓.

#For example
# " <-> '
# abc...z -> *
# ABC...Z -> AA, BB, CC, ...,ZZ
#If you want to make a replacement like

text = "'abc'" + '"ABC"'

#pattern 1
replaced_text = text.replace('"', '#').replace("'", '"').replace('#', "'").replace("a", "*"). ....... 

#Pattern 2
trdict = str.maketrans({'"': "'", "'": '"', "a": "*", "b": "*", .......})
replaces_text = text.translate(trdict)

#Pattern 3
import re
replaced_text = re.sub("#", '"', re.sub('"', "'", re.sub("'", '#', re.sub("[a-z], "*", re.sub("[A-Z]", "\\1\\1", text)))))

#etc...

In addition, in the case of replacement methods such as patterns 1 and 3, replacement is performed in order, so it is necessary to consider the possibility of unexpected replacement such as further replacement of characters after replacement. .. However, if you can't use regular expressions like pattern 3, it will take a lot of time and effort.

To eliminate such dissatisfaction

** You can also use regular expressions, You can pass the replacement patterns together in a dictionary, All replacements can be done at the same time **

I wrote a function.

What was made

import re
from typing import Dict

def replaces(text: str, trdict: Dict[str, str]) -> str:
    """
    IN:
        Source text
        Replacement dictionary
    OUT:
        Replaced text
        
    NOTE:
        You can use regular expressions.
        If more than one pattern is matched, 
        the pattern closest to the front of the dictionary takes precedence.
    
    EXAMPLE:
        text = "'abc'" + '"ABC"'
        replaces(text, {"'": '"', '"': "'", "[a-z]": "*", "([A-Z])": "\\1\\1"})
        
        ---> "***"'AABBCC'
    """
    return re.sub(
        "|".join(trdict.keys()), lambda m: next(
            (re.sub(pattern, trdict[pattern], m.group(0)) for pattern in trdict
             if re.fullmatch(pattern, m.group(0)))), text)

How to use

First argument: Original string Second argument: Replacement dictionary {before: after} Return value: Character string after replacement

text = "'abc'" + '"ABC"'
trdict = {"'": '"', '"': "'", "[a-z]": "*", "([A-Z])": "\\1\\1"}
replaces(text, trdict)
# ---> "***"'AABBCC'

If multiple patterns in the dictionary are matched, the previous pattern takes precedence.

Recommended Posts

[Python] I made a function that can also use regular expressions that replace character strings all at once.
I made a familiar function that can be used in statistics with Python
[Python R pyper] Can I use pyper.R inside a function? Solution
I made a package that can compare morphological analyzers with Python
[python] I made a class that can write a file tree quickly
[Python] A function that searches the entire string with a regular expression and retrieves all matching strings.
I made a character counter with Python
[Python] I made a decorator that doesn't seem to have any use.
[Python] I made a utility that can access dict type like a path
I made a module PyNanaco that can charge nanaco credit with python
I made a Docker image that can call FBX SDK Python from Node.js
[auto-ohin] Introducing auto-ohin, a command line tool that can automatically stamp all at once [electronic stamp]
I made a VM that runs OpenCV for Python
[Python] I made a function that decrypts AES encryption just by throwing it with pycrypto.
I made a tool to get the answer links of OpenAI Gym all at once
I made a function to crop the image of python openCV, so please use it.
I made a plug-in that can "Daruma-san fell" with Minecraft
Use regular expressions in Python
I made a python text
・ <Slack> Write a function to notify Slack so that it can be quoted at any time (Python)
Use the graphic LCD as a character LCD that can also display Chinese characters on the Rasberry Pi
[Python] I made a Line bot that randomly asks English words.
[Python3] I made a decorator that declares undefined functions and methods.
[Python] I made my own library that can be imported dynamically
I want to use a wildcard that I want to shell with Python remove
A memo that handles double-byte double quotes in Python regular expressions
[Python] I made an image viewer with a simple sorting function.
I made a library that adds docstring to a Python stub file.
Use regular expressions in Python
When using regular expressions in Python
Don't use \ d in Python 3 regular expressions!
How to use regular expressions in Python
[Python] Regular Expressions Regular Expressions
Python pandas: Search for DataFrame using regular expressions
Use regular expressions in C
Extract numbers with regular expressions
About Python and regular expressions
Ansible Jinja2 filters Replace and extract variable strings with regular expressions
slackbot memorandum ~ Request using regular expressions ~
I can't remember Python regular expressions
[Beginner] Extract character strings with Python
Extract the targz file using python
Handling regular expressions with PHP / Python
Extract strings from files in Python
[Python] I made a function that can also use regular expressions that replace character strings all at once.
Overlapping regular expressions in Python and Java
[Python] Use pandas to extract △△ that maximizes ○○
Replace non-ASCII with regular expressions in Python
[Road to intermediate Python] Use lambda expressions
Python: Simplified morphological analysis with regular expressions
I made a Line-bot using Python!
I can't remember Python regular expressions
I made a fortune with Python.
Replace all at once with sed
I made a daemon with Python
I made a web application in Python that converts Markdown to HTML
I made a note of Google colaboratory which can use Spleeter easily.
I made a Discord bot in Python that translates when it reacts
I made a simple timer that can be started from the terminal
Features of regular expression modules that I often use personally in Python
I made a tool that makes decompression a little easier with CLI (Python3)
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
[Python] A game that uses regular expressions when, where, who, and what
I made a function to see the movement of a two-dimensional array (Python)