Функция 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
Getting excited over the 6.6 sales? Ask yourself if you really need the item before adding it to your cart!
Consider using or repairing what you have, instead of replacing it. #ReduceReuseRecycle
Check out some tips here: https://www.youtube.com/playlist?list=PLPX9rYUbMZF3GLoLkP2Bxd0TelSHylBOu
It can be very tempting to do online shopping this circuit breaker period, but think about whether you really need it before you put it in your cart! #ReduceReuseRecycle
Dressing up as your favourite superhero this Halloween?
Get creative and make a costume using everyday household items. When you’re done, recycle or reuse what you can of your outfit, so that your superhero legacy will continue to live on 🦸♂️
#3Rs#ReduceReuseRecycle
Be a green champion by refusing disposable plastic bags and using a reusable bag. Marvel at the environmental gains you achieve on a daily basis 💪#3Rs#ReduceReuseRecycle
✨ Like training dragons, recycling right takes practice. Master these 3 moves to #RecycleRight: Empty ➡️ Rinse ➡️ Dry
♻️www.nea.gov.sg/3R#3Rs#ReduceReuseRecycle#TowardsZeroWaste#SustainableSG
60 years of progress, but what’s next for Singapore?
Higher temperatures, more wet and dry extremes, and accelerating increase in mean sea levels are projected. In the worst-case scenario, the 𝗺𝗲𝗮𝗻 𝘀𝗲𝗮 𝗹𝗲𝘃𝗲𝗹 around Singapore is projected to 𝗿𝗶𝘀𝗲 𝗯𝘆 𝟭.𝟭𝟱𝗺 𝗯𝘆 𝘁𝗵𝗲 𝗲𝗻𝗱 𝗼𝗳 𝘁𝗵𝗲 𝗰𝗲𝗻𝘁𝘂𝗿𝘆, and up to 𝗮𝗿𝗼𝘂𝗻𝗱 𝟮𝗺 𝗯𝘆 𝟮𝟭𝟱𝟬.
Let’s commit to a sustainable future by taking climate actions to reduce our waste and carbon footprint. #3Rs#ReduceReuseRecycle#SG60
Happy 60th National Day, Singapore! 🇸🇬
As we celebrate our progress as a nation, let’s also commit to building a #SustainableSG for present and future generations. Let’s reduce our carbon footprint by taking climate actions such as adopting energy-saving and #ReduceReuseRecycle habits.
#SG60#KeepSGClean
#ProTip: There’s no need to sort your recyclables! Paper, plastic, glass, and metal can all be placed in the recycling bins ♻️✌️
But do remember to CHECK and CLEAN before you RECYCLE: www.go.gov.sg/recycleright
#RecycleRight#ReduceReuseRecycle
Give your home a refreshed look that brings renewed fortune to every corner.
Revamp your space by rearranging your furniture or upcycling your Lunar New Year decorations.
#3Rs#ReduceReuseRecycle#SustainableSG#TowardsZeroWaste#LunarNewYear2024
Switch off for #EarthHour at 8:30pm!
But let's not stop there. Let this yearly reminder inspire us to continue making sustainable choices. Your everyday choices matter more than you might think!
Small steps such as adopting energy-saving habits and recycling right can make a difference. Imagine these small acts being amplified by millions worldwide. 🌍💚
#EnergyEfficiency#ReduceReuseRecycle#RecycleRight
Building climate resilience will keep Singapore steady pom pi pi for the next 60 years! 💃🕺
Let’s take action for a #SustainableSG by adopting energy-saving and #ReduceReuseRecycle habits.
#SG60#ClimateActionSG
Tidying up your house over the weekend?
Here’s a #SustainabilityHack to keep your table free of messy wires! You can also beautify this DIY cable organiser to match your room design.
#3Rs#ReduceReuseRecycle#SustainableSG