Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
#nostalgiaMahalladagi 10ta kompyuteri bor kompyuterxona, soati 500 so'm bo'lgan paytlar va bir talay o'yinlar😄
➖➖➖➖➖➖➖➖➖
📍Manzil: [ Kichik halqa yo'li 8A ]
⏰ Ish vaqti: [10:00 dan 20:00]
📞 +998338082030
🔵@Comping_admin
➖➖➖➖➖➖➖➖➖
🔵Telegram📷Instagram🟥Youtube
We have all got our “good old days” tucked away inside our hearts, and we return to them in dreams like cats to favorite armchairs.
—Brian Carter
#happiness#nostalgia#life
@quietworld🍃
💿 The Rise and Fall of the Compact Disc
Having been hit by the rise of MP3 players in the early 2000s, #CD sales nearly halved between 2000 and 2007, which is when smartphones and the first music streaming services emerged to put the final nail in the compact disc’s little round coffin.
#Nostalgia
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
✨Get ready for a blast from the past! It's Retro Day! 🎮🎶
Mark your calendars for May 18, this Thursday, as we transport ourselves back to the magical era of our childhood. 🌟
Join us for a day filled with nostalgia, colorful retro games, and the iconic music that defined our younger years. 🕹🎵
We've curated an exciting lineup of classic games that will make you feel like a kid again. From Tetris to Domino, there's something for everyone to enjoy! Let's relive those epic gaming moments together. 🎮👾
Don your favorite retro outfits and get ready to immerse yourself in the vibrant atmosphere of our childhood. From neon colors to leg warmers, let's embrace the fashion trends that defined an era. It's time to bring back the style! 👕👖
Date: May 18, Thursday
Time: Whole day
Location: New Uzbekistan University
Spread the word and let's make this Retro Day a celebration of our shared past! See you there! 🎉✨
#RetroDay#Nostalgia#ChildhoodMemories
Best Regads,
Student Government.
First Love Should Be Forever... Right? 💔#shorts#cinema#firstlove#loveforever#heartbreak#romance#relationships#emotions#cinematic#lovequotes#drama#nostalgia#movingon
https://pdmovies.substack.com/p/the-big-combo-1955
L'attaccamento agli oggetti é uno degli ostacoli maggiori per la nostra felicità, come se infondessimo in essi parte della nostra anima.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#disagio#nostalgia#illusione#illusion#windows95#windows98#windowsxp