Функция 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
Voiceover Translator Needed (English ➡️ Indian Language)
#remote#english#indian#tango
NKS Media Agency is looking for talented translators to work on our short video content.
Languages We Need: Indian
What You'll Do: Translate English scripts into your target language and prepare them for AI voiceover. The goal is clear, natural-sounding audio. Check out an example: https://youtube.com/shorts/MkRlgmLdNnM.
Note: Since we use AI for voiceovers, your script adaptation for spoken clarity is key!
What We're Looking For:
• Strong English or Russian and target language skills (B2+).
• Impeccable grammar.
• Reliability and ability to meet deadlines.
• A reliable computer and internet connection.
What We Offer:
• Fully remote position with a flexible schedule.
• $3 per video.
• Focus on creating clear, audible translations.
Ready to Apply? Send your CV and translation samples to [email protected] or DM us on Telegram: t.me/nks_HR. Please use the subject: "Translator [English - Target Language]".
⏺Apply: t.me/nks_HR
➖➖➖➖➖➖➖➖➖➖➖
🪩 Откликнуться быстрее других
➖➖➖➖➖➖➖➖➖➖➖
#DYOR#Advertisement#Indian#Sponsored
💸🎁😳 V I P 2️⃣➕ L U C K Y D R A W 😳🎁💸
rummytryag.com?from_gameid=8197351&channelCode=8184357
✊Instantly access the⌨️⌨️⌨️⌨️⌨️⌨️⌨️⌨️⌨️⌨️⌨️ rewards!🤑
Don't delay, log in now to take part in the Weekly Bonus and claim your substantial rewards!🍀
Deposit 😀₹1️⃣0️⃣0️⃣0️⃣ and seize the exclusive chance to be among the top 2️⃣0️⃣ spots, with each rewarded 😀₹1️⃣0️⃣0️⃣0️⃣.
Every Monday 1️⃣4️⃣🔣0️⃣0️⃣0️⃣⏰
🔴JOIN NOW AND EARN MORE🔴
rummytryag.com?from_gameid=8197351&channelCode=8184357
🎉Enhance your gaming journey with fantastic benefits! Seize the opportunity to enrich your gaming experience.💩
World Court sides mostly with Somalia in border dispute with Kenya
The top U.N. top court ruled on Tuesday largely in favor of Somalia in its dispute with Kenya, setting a sea boundary in part of the Indian Ocean believed to be rich in oil and gas.
#Somalia#Kenya#UN#ICJ#Indian Ocean #News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
In the Indian state of Kerala, the sculptor carved the statue of Trump and Melania as the embodiment of the Indian gods Shiva and Kali. Thus Trump has entered the Pantheon of Hindu gods.
#indian#state#kerala#trump#pantheon
👂More on Trump's Ear ⚠️
🌟EAR BUDS @ ₹39🌟
🔥LOOT DEAL OF THE DAY🔥
🛍Grab fast before it gets Out of stock. Get similar deals in future by joiningLoot Indian Deals🛍
🔰Note- Check all deals instantly 🔰
#Loots#Indian#Deals#offers
"#Tharparkar Cows" - a #Desi#cow breed found mostly in North Western India. "Thar+par+kar" name derives from the fact that they can cross the Thar desert without any difficulty.
Hindu #Indian#tharparkar#gomata😍 Join @LovelyNature
🚨Game : TC Games
🤑Refer: High Level Commission
🛃Minimum Deposit : 300Rs
📅Minimum Withdraw : 110Rs
🖥Earn daily : 500-10keasily
🤖Game Link: Join Here
📝Guide:
🔘 Register Using Mobile Number
🔘 Play game and Withdraw and earn High money
🧿Info
🔘 Contact Telegram Support
🔘 Join Telegram Prediction Group1 and Group2
🔘 Only 4-7 Level Sure winning
🔘 Want to become an agent and bonus Contact
🔴Note: Please do your own research (DYOR) before joining to any project.Don't send any fee or penny without doing own research.
#TCgames#TcLottery#Indian#inr#TC#Sponsored#Ad