Функция 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
🌎 Perched atop a limestone cliff, the Italian town of Civita di Bagnoregio is slowly crumbling away as erosion eats at its base. Only about 12 people reside year-round, and the settlement is accessible by a pedestrian bridge spanning a deep valley. ✨
#geography⚡#architecture⚡#erosion
👉subscribe Interesting Planet
👉more Channels
🌍 Some coastlines in Alaska lose up to 20 meters of land each year from a mix of sea ice loss, stronger storms, and thawing ground, making it one of the fastest-eroding coastlines worldwide. ✨
#erosion⚡#coastline⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some sea stacks—towering rock columns near coastlines—form when waves erode cliffs, leaving only isolated pillars. Ireland’s Dun Briste sea stack stands 50 meters above the Atlantic. ✨
#coastline⚡#erosion⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In some places, rising sea levels have pushed salty ocean water far inland, turning once-fresh coastal farmland into wetlands and forcing communities to change how and where they grow crops. ✨
#erosion⚡#sea-level ⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In some places, coastal cliffs are vanishing so quickly that entire villages have moved inland within a single generation, as sea level rise and stronger storms speed up the erosion. ✨
#erosion⚡#coastlines⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In some low-lying Pacific islands, entire villages have relocated inland as coastal erosion worsens from rising sea levels, erasing beaches and farmland within a single generation. ✨
#erosion⚡#sea-level ⚡#islands⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Rainwater can carve entire underground labyrinths in karst landscapes, creating vast networks of caves, tunnels, and sinkholes—some so deep and complex that new passages are still being found today. ✨
#caves⚡#karst⚡#erosion⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Coastal erosion is eating away cliffs and beaches so fast in some places that detailed maps need updating every year, with new shorelines appearing and disappearing before our eyes. ✨
#coastlines⚡#erosion⚡#mapping⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the last 30 years, parts of Louisiana’s coast have lost over 2,000 square kilometers of land to erosion and rising seas—an area bigger than many cities, disappearing into open water. ✨
#erosion⚡#sea-level ⚡#wetlands⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In some regions, sea level rise combines with sinking land, making coastal erosion even faster. This double impact is shrinking important wetlands and salt marshes much quicker than before. ✨
#erosion⚡#wetlands⚡#sea-level ⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Coastal erosion now removes up to 24 square meters of land per meter of shoreline in some parts of West Africa each year, forcing whole fishing villages to move further inland. ✨
#coastlines⚡#erosion⚡#sea-level ⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Satellite data shows that some coastlines have retreated by over 50 meters in just a decade, as rising sea levels and stronger storms rapidly reshape shores across the globe. ✨
#erosion⚡#sea-level ⚡#coastlines⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels