Функция 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
🌍 Earth’s core is as hot as the surface of the Sun, reaching temperatures around 5,400°C. This intense heat drives movements deep inside the planet that power volcanoes and earthquakes. ✨
#planet⚡#core⚡#heat⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Myth: Glass flows over time, making old windows thicker at the bottom.
Fact: Glass is an amorphous solid, meaning its atoms are arranged randomly, not in a pattern like crystals. It stays solid at all normal temperatures and only softens above 600°C (1112°F). Old windows are thicker at the bottom because of how they were made, not because glass moves. 🔥🌡️
[Read more]
@googlefactss
#GlassFacts#Science#MythBusted#Heat
🪐 The exoplanet Gliese 367 b, located about 31 light-years away in the constellation Vela, completes an orbit in just 7.7 hours and endures surface temperatures over 1,500°C—hot enough to melt iron. This "ultra-short period" planet is likely a dense, iron-rich world blasted by so much stellar radiation that any atmosphere or lighter materials have long since been stripped away, leaving behind a scorched metallic core. ✨
#exoplanets⚡#extremes⚡#heat⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Exoplanet Kepler-70b, found in the constellation Cygnus, endures some of the most extreme conditions in the galaxy—it’s so close to its star that surface temperatures reach about 7,000°C, hotter than most stars and easily hot enough to vaporize rock. This planet orbits its star in just 5.7 hours, making it one of the fastest-orbiting planets ever discovered and a true survivor in a scorching, hostile environment. ✨
#exoplanets⚡#extremes⚡#heat⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Far from Earth, the exoplanet TOI-1431b (also known as MASCARA-5b) orbits so close to its star that its dayside temperature can reach about 2,700°C—hotter than molten lava. Even the nightside sizzles at a blistering 2,300°C, making TOI-1431b one of the hottest planets ever discovered and a true furnace world where no familiar material could survive. ✨
#exoplanets⚡#extremes⚡#heat⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The exoplanet KELT-9b, orbiting a star about 670 light-years away in Cygnus, is one of the most extreme worlds ever found—its dayside temperatures soar above 4,000°C, hotter than some stars. Metal atoms like iron and titanium are vaporized in its atmosphere, creating a blistering, glowing layer of gas that defies what we imagine for planets outside our solar system. ✨
#exoplanet⚡#extremes⚡#heat⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
♨️🌡The heat is on: Moscow temperatures are breaking records
Meteorologists claim that July 2, 3 and 4 could be the hottest days of this month in the history of meteorological observations in the capital since 1879. The air will warm up to 33-35 degrees, which is 10 degrees higher than the July climate norm.
On Friday, July 5, things should return closer to normal. Thermometer readings will drop to 24–28 degrees during the day, and to 15–18 at night. This is also above the climatic norm, but by one or two degrees.
Subscribe:@nido_russia
https://t.me/nido_russia/1688
#heat#weather#forecast#hot#record#nidorussia
🎬📷 Атмосферные фото со съёмок фильма «Схватка».
В этот день ровно 30 лет назад шедевр Майкла Манна вышел на большие экраны.
#ВИДЕОТЕКА
#Heat
#Схватка
#RobertDeNiro
#РобертДеНиро
#AlPacino
#АльПачино
#ValKilmer
#ВэлКилмер
#MichaelMann
#МайклМанн
#AshleyJudd
#ЭшлиДжадд
#TomSizemore
#ТомСайзмор
#BehindTheScenes
«Когда мы снимали сцену в кафе в фильме «Схватка», мы практически не проводили репетиций. Специально. Обсудили только общие моменты и хронометраж. Просто прошлись по тексту, потому что работу актеров я хотел увидеть только при съемке. А снимал я сразу на несколько камер, потому что понимал, что с такими актерами, как Аль и Боб, важна каждая деталь. Если Аль делает движение рукой, то Боб автоматически реагирует и меняет позу. Это органичное взаимодействие невозможно предугадать. В каждом дубле появляется что-то новое. Вот почему я всегда делаю ставку на спонтанность. Кстати, вся эта сцена в «Схватке» в итоге снята одним дублем. Но, в конечном счете, фильм получается таким, как я хочу».
🎬📷Сегодня исполнилось 83 года великому режиссёру, продюсеру и сценаристу Майклу Манну.
#ВИДЕОТЕКА
#MichaelMann
#МайклМанн
#Thief
#Вор
#TheLastOfMohicans
#ПоследнийИзМогикан
#Heat
#Схватка
#Ali
#Али
#Collateral
#Соучастник
#MiamiVice
#ПолицияМайамиОтделНравов
#PublicEnemies
#Blackhat
#Ferrari
#Феррари
#BehindTheScenes
«Если Марти попросит меня о чем-то, я буду думать об этом всерьез — даже если это покажется мне неинтересным».
Сегодня Роберту Де Ниро исполнилось 82 года.
#ВИДЕОТЕКА
#RobertDeNiro
#РобертДеНиро
#TheGodfatherPartII
#КрестныйОтец2
#TheDeerHunter
#ОхотникНаОленей
#RagingBull
#БешеныйБык
#OnceUponATimeInAmerica
#ОднаждыВАмерике
#MidnightRun
#УспетьДоПолуночи
#Casino
#Казино
#Heat
#Схватка
#Ronin
#Ронин
#TheIntern
#Стажер
#TheIrishman
#Ирландец