Функция 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
Вечерний Ереван 🌟
International youth cooperation is an important part of humanitarian policy around the world❤️
Международное сотрудничество по линии молодёжи — это важная часть политики во всем мире 😀
#Diplomatic
Для меня любая поездка — это возможность отдохнуть и перезагрузиться.
В этот раз я чувствовал ответственность, выступая перед публикой на серьёзную тему: медийно-информационная грамотность подростков в интернете.
Эта поездка запомнилась мне большим путешествием по Еревану и множеством положительных эмоций. Отдельная благодарность за всё это — Северо-Кавказскому институту филиала ВГУЮ❤️
Я защищал научную работу среди других участников, в том числе из Армении.
Интересно, что в Ереване, особенно в центре города, расположено множество посольств. Это дало мне уникальную возможность увидеть их своими глазами и даже посетить одно из них)
#ARMENIA#Diplomatic#molod
ICC CASE AGAINST URSULA Von Der LEYEN - FOR COMPLICITY IN WAR CRIMES AND CRIMES AGAINST HUMANITY IN GAZA
Today the International Criminal Court (#ICC) has been officially called to investigate Ursula von der Leyen for #complicity in acts of #Genocide.
Reasonable grounds exist to believe that the unconditional support of the president of the #European Commission to #Israel – #military, #economic, #diplomatic and #political – has enabled #WarCrimes and the ongoing genocide in #Gaza.
– A communication is submitted today to the Office of the Prosecutor of the International Criminal Court (ICC), setting forth in detail, through facts and evidence, that there are reasonable grounds to believe that the current president of the European Commission, Mrs. Ursula von der Leyen, a national of Germany, is complicit in a number of violations of international humanitarian law, amounting to crimes within the jurisdiction of the ICC, committed by the Israeli armed forces (#IDF) against #Palestinian civilians in the #Occupied Palestinian Territory (#OPT), including the #Gaza Strip.
This communication, endorsed by various human rights groups and prominent academics and experts in international criminal law, calls the Prosecutor to initiate investigations on the basis of the information provided against Mrs. Ursula von der Leyen.
The communication documents in detail the fact that Mrs. Ursula von der Leyen personally is criminally responsible and liable for punishment for some of the war crimes, #CrimesAgainstHumanity and #genocide having been committed (and still being committed) by the Israeli armed forces in the #OPT, to the extent that she has aided, abetted and otherwise assisted in the commission or attempted commission of such crimes, including providing the means for its commission, in the meaning of Article 25(3)(c) of the #RomeStatute of the #ICC.
MRS. VON DER LEYEN ENJOYS NO FUNCTIONAL IMMUNITY BEFORE THE ICC BY VIRTUE OF ARTICLE 27 OF THE ROME STATUTE.