Функция 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
"We are living in unprecedented times, but with fortitude and resilience, we can and will stand in solidarity as one united Singapore – to beat this crisis and emerge stronger as a nation." -- DPM Heng Swee Keat
#SGTogether#SGUnited
Catch Mr Liang Eng Hwa’s LIVE interview on Capital 95.8FM Tonight, 6.30pm!
Join us in discussing the Budget, Digitalisation & Jobs and national issues! Also find out what our citizens have to say through feedback collected by REACH. Stay tuned!
#SGUnited#SGTogether
More: https://www.facebook.com/92744267226/posts/10157332345052227
As we approach the end of the Circuit Breaker, measures will be progressively lifted in three phases from 2 June. Many restrictions in place will continue in Phase 1.
#SGUnited#SGTogether.
The Government announced that there will be gradual easing of Circuit Breaker measures. What are the services that will resume operation? Find out here!
#SGUnited#SGTogether
In our compact city, planning for the many different land use needs is often like a balancing act. By working together, we can make future Singapore a space for our hopes and dreams.
We've just launched Phase 2 of the Long-Term Plan Review public engagement exercise - come share your ideas at: go.gov.sg/ltpr
#LTPR2021#SGTogether
💡What do you value more in shaping a liveable Singapore: a good transportation network, convenient access to amenities, greenery in the city or the other factors above?
We're calling for your views and ideas in our online poll for the Long-Term Plan Review. With your participation, we can develop long-term land use plans that will better meet your needs and aspirations as well as those of future generations!
Tell us more at: go.gov.sg/ltpr
#LTPR2021#SGTogether
📣 We just launched our public engagement for the Long-Term Plan Review (LTPR) today and are excited to develop plans for Singapore's next chapter with you over the next year!
The #LTPR2021 is the latest review of plans that will steward land resources not just for today's use but also for future generations over the next 50 years and beyond.
We'd love to hear your hopes and aspirations for the future to develop these long-term plans! Watch how long-term planning has shaped the everyday lives of fellow citizens as well as what they dream for our future city - and share your dreams with us in our online poll at go.gov.sg/ltpr
#SGTogether
Where there are wet and dark crevices, NEA’s Dengue Inspection Officer Marthandan will be there. Let him show you how he and his team spot and tackle mosquito breeding in the areas around you!
Join him in our #NEAOfficers Story Highlight on our Instagram profile (www.instagram.com/nea_sg)!
#SGUnited#SGTogether
It has been more than a year since COVID-19 happened. Many of us have had to adapt to new work situations and overcome the various challenges the pandemic brought with it.
Today, we salute all workers, especially the frontliners who have been working extra hard to keep us safe this past year.
Happy Labour Day! 💪🇸🇬
#SGUnited#SGTogether
This National Day, let us celebrate the Singapore spirit that has kept us going during the most challenging of times. It will continue to help us emerge stronger for the future.
Happy 56th Birthday, Singapore!
#TogetherOurSGSpirit#SGUnited#SGTogether