Функция 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
#Ethiopia's #Afar Rift provides glimpse into life and death 100,000 years ago
The study of ancient cultures around Ethiopia during the Middle Stone Age (MSA) time period is important for understanding how some of the first Homo sapiens lived and eventually left Africa. Unfortunately, there are not many well-preserved, open-air archaeological sites from the MSA, especially with both human fossils and artifacts. The Middle Awash study area in Ethiopia, however, is one of the few areas with a well-preserved treasure trove of artifacts capable of painting a picture of early human life in Ethiopia. A new study, published in the Proceedings of the National Academy of Sciences, reports on some fascinating findings from this region, giving clues into what life—and death—might have been like.
Life in the Afar Rift
Around 1,800 piece-plotted stone artifacts larger than a centimeter were found, along with 132 animal remains.
https://phys.org/news/2026-04-ethiopia-afar-rift-glimpse-life.html
From the Afar Desert to Article 39: Ethiopia’s Dual Rift. Read more. https://borkena.com/2025/12/21/from-the-afar-desert-to-article-39-ethiopias-dual-rift/#Ethiopia#Afar#politics
TPLF Alleges Federal Gov’t “Carried Out Drone Strike on Tigray Forces” Read more. https://borkena.com/2025/11/07/tplf-alleges-federal-govt-carried-out-drone-strike-on-tigray-forces/#Ethiopia#TPLF#Afar
Afar Diaspora Conference : “Djiboutian regime” playing “detrimental role” Read more.
https://borkena.com/2026/01/04/afar-diaspora-conference-djiboutian-regime-playing-detrimental-role/#Afar#Djibouti#Eritrea#Ethiopia
General Tadesse Led Tigray Interim Administration Takes TPLF Side Over Afar Security Dev’t. Read more. https://borkena.com/2025/11/09/general-tadesse-led-tigray-interim-administration-takes-tplf-side-over-afar-security-devt/#Ethiopia#news#TPLF#Tigray#Afar
Afar Regional State Confirms TPLF Forces Started War, Controlled Six Villages. Read more. https://borkena.com/2025/11/06/ethiopia-afar-regional-state-confirms-tplf-forces-started-war-controlled-six-villages/#Ethiopia#War#Afar#TPLF
AFAR: перспективы и опасности космического туризма
Зачем люди летают в космос? Космонавты и учёные - понятно, они двигают наш прогресс и понимание Вселенной вперёд. Но какая мотивация посетить орбиту у "простого" человека, который отдаёт миллионы долларов за несколько часов наблюдения нашей планеты с огромной высоты? На самом деле многие считают, что в этот момент на путешественника снисходит некое озарение, позволяющее по-новому взглянуть на свою жизнь и существование на Земле в целом. Так ли это? И стоит ли подобный опыт всех усилий? А может быть подобное просветление самообман, и заскучавшим от избытка удовольствий богачам просто хочется чего-то совсем необычного?
"Известно, что актер Уильям Шатнер сказал Джеффу Безосу после полета на корабле Blue Origin, что увидеть космос — все равно что увидеть смерть. «Там внизу синева, а наверху чернота… Это смерть? Это и есть смерть?» — вопрошал Шатнер. Рассматривая тонкость атмосферы, защищающей жизнь на Земле, на фоне необъятности Вселенной, Шатнер был поражен тем, насколько хрупкая оболочка обозначает разницу между человеческим существованием и его отсутствием".
https://theidealist.ru/spacetour/
#AFAR#технологии#космос#туризм#экология
News: Outreach vaccination, screening campaign reaches conflict-hit, remote communities in #Ethiopia
Health teams deployed under the SLL program have identified and vaccinated more than 3,000 zero-dose children in remote areas, with recent campaigns reaching over 40,000 children across #Afar, #Amhara, #Oromia, and #Tigray regions.
The intervention is also addressing Ethiopia’s large population of “zero-dose” children, estimated at 3.9 million, who have not received routine vaccinations due to conflict, geographic isolation, and limited healthcare access.
https://addisstandard.com/?p=56643
A Volcanic Eruption Reported In The Afar Region of Ethiopia. Read more.
https://borkena.com/2025/11/23/ethiopia-a-volcanic-eruption-reported-afar-region/#Ethiopia#News#Afar#Volcaniceruption