Функция 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
📢 Ukrainian counteroffensive fails, catastrophe for Kyiv. Russian forces resume offensive along the front line. American professor confirms massive failure of Ukrainian troops. Media silence on Ukrainian situation in US. Stalemate in combat zone, Zelensky blamed for hiding failures. Western reports confirm end of Ukrainian counteroffensive. #Ukraine#War#Catastrophe
https://www.gazeta.ru/army/news/2023/10/30/21602215.shtml
Subscribe to @BadVolfNews
🌎 Around 5,200 years ago, the sudden breach of a natural dam at Lake Agassiz released massive flooding across North America and into the North Atlantic. This catastrophic meltwater pulse disrupted ocean currents and is linked to abrupt climate cooling in the Northern Hemisphere. Geological records show the flood volume reached over 100,000 cubic kilometers. ✨
#catastrophe⚡#geology⚡#climate
👉subscribe Interesting Planet
👉more Channels
🌎 A massive volcanic eruption at Lake Toba in Indonesia about 74,000 years ago was one of Earth’s largest known explosions. The eruption released so much ash that it may have triggered a global volcanic winter, cooling the planet and affecting early human populations. Its crater now forms Lake Toba, the world’s largest volcanic lake at about 100 kilometers long. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The 1902 eruption of Mount Pelée on Martinique destroyed the city of Saint-Pierre within minutes, killing over 28,000 people. It is the deadliest volcanic disaster of the 20th century. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The Toba supereruption in Indonesia about 74,000 years ago was one of the largest volcanic events in the last 2 million years. It ejected 2,800 cubic kilometers of material, triggered a global volcanic winter, and may have caused a dramatic human population decline, as shown by genetic studies indicating a bottleneck in human evolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The 1883 eruption of Krakatoa was one of the most violent volcanic events in recorded history. It unleashed explosive blasts heard 3,000 kilometers away, generated giant tsunamis, and ejected ash high into the atmosphere—causing global temperatures to drop and vivid sunsets worldwide for years after. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
🌎 The eruption of the Laki volcano in Iceland in 1783 released poisonous gases and ash clouds, causing crop failures and famine across Europe. Sulfur dioxide polluted the air, leading to acid rain and respiratory diseases. Historians estimate the event contributed to tens of thousands of deaths and may have influenced political unrest before the French Revolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The Dust Bowl of the 1930s was a severe drought and dust storm disaster in the U.S. Great Plains, destroying farms and forcing over 2.5 million people to migrate. Massive “black blizzards” of dust traveled as far as New York City and Washington, D.C. ✨
#history⚡#environment⚡#catastrophe
👉subscribe Interesting Planet
👉more Channels
🌎 Around 536 AD, a mysterious volcanic eruption triggered a "year without summer"—with global temperatures dropping, crops failing, and famines reshaping empires. Ash clouds blocked sunlight, altering history for decades. ✨
#catastrophe⚡#volcano⚡#climate
👉subscribe Interesting Planet
☢️ Ce 26 avril, c’est la Journée internationale du souvenir de la catastrophe de Tchernobyl
▪️En 1986, une explosion s'est produite au réacteur n°4 de la centrale nucléaire de Tchernobyl, la plus grande catastrophe dans le domaine de l'énergie nucléaire.
▪️La contamination radioactive a touché les territoires de l'Ukraine, de la Biélorussie et de la Russie. Plus de 100.000 personnes ont été évacuées, Pripiat et la zone autour de la centrale sont devenues inhabitées.
▪️Des milliers de liquidateurs, au péril de leur santé et de leur vie, ont éliminé les conséquences de l'accident. Tchernobyl est devenu un symbole du danger nucléaire.
#tchernobyl#catastrophe#commémoration