Функция 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
🌎 The Falkland Islands are home to the only known population of the Cobb’s wren, a small brown bird found nowhere else on Earth. These birds thrive in predator-free habitats, showing how isolated islands can protect unique species from extinction. ✨
#biodiversity⚡#islands⚡#birds
👉subscribe Interesting Planet
🌎 Border oddities abound in Earth’s geography! The Diomede Islands, just 4 km apart in the Bering Strait, belong to different countries and are separated by the International Date Line, meaning they are 21 hours apart in time despite being visible from each other. ✨
#geography⚡#borders⚡#islands
👉subscribe Interesting Planet
🚤Nusa Penida could be home to a floating hospital
🏥 Nusa Penida leaders are proposing a water ambulance service to respond quickly to emergencies.
🚨 There are currently no major hospitals on the islands of Nusa Penida, Nusa Lembongan and Nusa Ceningan near Bali. The small clinics that do exist are unable to treat emergencies and patients have to be brought to Bali by boat or evacuated by helicopter.
@BaliNews
#goodnews#health#islands
🌍 One of the youngest islands on Earth, Hunga Tonga-Hunga Haʻapai, formed in 2015 after an undersea volcanic eruption. New land like this is rare and offers scientists a natural laboratory. ✨
#islands⚡#volcanoes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 The double coconut palm of Seychelles produces the world’s heaviest seed—up to 18 kilograms! Its giant, heart-shaped seed takes years to mature before dropping to the forest floor. ✨
#botany⚡#islands⚡#wonders
👉subscribe Interesting Planet
🌍 The Canadian Arctic Archipelago includes over 36,000 islands, making it one of the most complex island groups on Earth. These remote lands are mostly uninhabited and covered by ice much of the year. ✨
#islands⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Canada’s Manitoulin Island is the largest freshwater island in the world. It’s so big that it contains more than 100 lakes, and some of those lakes have islands of their own. ✨
#islands⚡#freshwater⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
The Philippines is an archipelago with about 7,641 islands. Around 2,000 islands are inhabited. More than 5,000 islands are unnamed. The islands are grouped into Luzon, Visayas, and Mindanao. The older count of 7,107 islands was updated after modern surveys.
🇵🇭🏝️🌊
[Read More]
@googlefactss
#Philippines#Islands#Geography#DidYouKnow#Facts
🌍 In recent decades, a growing number of small island nations are seeing rising sea levels drive migration, forcing some communities to relocate entirely from their ancestral homes. ✨
#migration⚡#islands⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The ancient terraces of the Canary Islands blend natural volcanic slopes with centuries-old farming. These landscapes are so unique they’re recognized globally as a heritage site. ✨
#heritage⚡#agriculture⚡#islands⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Indonesia is the world’s largest archipelago, made up of over 17,000 islands. Some, like Java, are densely populated, while others remain so remote they still hold undiscovered plant species. ✨
#archipelago⚡#islands⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels