Что-то вроде подробной опции, это возможно ли, чтобы re.sub распечатывал сообщение каждый раз, когда он производит замену? Это было бы очень полезно для тестирования того, как несколько строк re.sub взаимодействуют с большими текстами.
Мне удалось найти обходной путь для простых замен с использованием тот факт, что аргумент repl может быть функцией:
Код: Выделить всё
import re
def replacer(text, verbose=False):
def repl(matchobj, replacement):
if verbose:
print(f"Replacing {matchobj.group()} with {replacement}...")
return replacement
text = re.sub(r"[A-Z]+", lambda m: repl(m, "CAPS"), text)
text = re.sub(r"\d+", lambda m: repl(m, "NUMBER"), text)
return text
replacer("this is a 123 TEST 456", True)
# Log:
# Replacing TEST with CAPS...
# Replacing 123 with NUMBER...
# Replacing 456 with NUMBER...
Код: Выделить всё
def replacer2(text, verbose=False):
def repl(matchobj, replacement):
if verbose:
print(f"Replacing {matchobj.group()} with {replacement}...")
return replacement
text = re.sub(r"([A-Z]+)(\d+)", lambda m: repl(m, r"\2\1"), text)
return text
replacer2("ABC123", verbose=True) # returns r"\2\1"
# Log:
# Replacing ABC123 with \2\1...
Подробнее здесь: https://stackoverflow.com/questions/781 ... t-it-makes