Функция 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
🎊🎉🍾🇳🇬🇷🇺
Our beloved organisation, NIDO Russia has been officially accepted as a full member of NIDO Europe yesterday evening 01.02.2025 by the overwhelming majority of the general house which is the supreme organ. We owe this success to our faithful members, the board of trustees, the chairmen Emeritus and stakeholders.
Recall that, a tiny group of people prevented this for many years, saying that we must be part of their cabal for our rights to be respected in Europe. We rejected their ideas and protocols, we refused to be gradually assimilated, we took our destiny in our hands, knowing God was on our side. Their condition for peace was that we stoop low and be under them. We rejected that kind of parasitic peace. This group said it was either their way or the highway. We chose the beautiful highway. You must not be a doctor or lawyer or teacher to be part of NIDO Russia or NIDO Europe. Every Nigerian legally residing in Russia has a right to apply to be part of us. Even those who may not yet be fully legal, it is not our duty to judge or condemn them, but rather to guide them (socioeconomically adapt them) towards legalisation and contributing positively to Russia and their families in Nigeria.
It is a huge lesson for us all. "Na who give up, na him lose".
Nevertheless, we are open to working together with everyone for our common good including those few people who worked against us. It is a new era.
What are the benefits of being part of NIDO Europe?
1. The interests of Nigerians in Russia can be represented on a continental level.
2. The interests of the Russian Federation which are also our interests as residents can be represented on a continental level
3. Better negotiating power with the government on matters important to us as Diasporans.
4. Better synergy of efforts towards national development, bilateral trade, foreign direct investments and human capital development.
I, on behalf of the executives congratulate us all for this huge achievement including those members who witnessed it live and direct.
Yours in service,
Dr. Godwin Ibe
https://t.me/nido_russia/1937
#NidoRussia#NidoEurope#NIDO#NidoE#Nigeria#Russia
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm