Функция 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
Embark on a journey of progress and transformation! 🚀
Visit https://9years.mygov.in/ to discover the incredible achievements of the Modi Government in the last 9 years. Explore the remarkable strides made across various sectors, from healthcare to infrastructure, education to governance.
#9YearsOfSeva
🇮🇳 In 9 years, the Modi Government achieved an unprecedented combination of speed and scale, ensuring the timely completion of all projects!
From highways and airports to digital infrastructure, India witnessed an era of efficient governance that propelled progress at an unmatched pace.
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
"सेवा, सुशासन और गरीब कल्याण को सर्मपित 9️⃣ साल" 🇮🇳
आइए इस वीडियों के माध्यम से देखें कैसे, बीते 9 वर्षों में #NewIndia जनसामान्य की आकांक्षाओं को पूरा करते हुए निरन्तर नई-नई उपलब्धियां रच रहा है।
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
"सेवा, सुशासन और गरीब कल्याण को सर्मपित 9️⃣ साल" 🇮🇳
आइए इस वीडियों के माध्यम से देखें कैसे, बीते 9 वर्षों में #NewIndia जनसामान्य की आकांक्षाओं को पूरा करते हुए निरन्तर नई-नई उपलब्धियां रच रहा है।
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
बीते 9 वर्षों में माननीय प्रधानमंत्री #NarendraModi के नेतृत्व में केंद्र सरकार द्वारा विभिन्न क्षेत्रों में हुई अविश्वसनीय उपलब्धियों को जानने हेतु अभी विजिट करेः https://9years.mygov.in/
#9YearsOfSeva
Don't miss this remarkable video showcasing how the Modi government's relentless efforts over the past 9 years have propelled the development and preservation of India's rich cultural heritage.
Visit: https://youtu.be/scGbw2m8ook
#9YearsOfPreservingCulture
#9YearsOfSeva
Check out this captivating snapshot showcasing the Modi government's remarkable progress in preserving and promoting India's cultural heritage. From restoring ancient monuments to revitalizing traditional arts, their efforts over the past 9 years have made India's legacy shine brighter than ever.
#9YearsOfPreservingCulture
#9YearsOfSeva
📈 India keeps dominating the digital payment landscape! 💸🇮🇳 With innovative solutions and widespread adoption, we're leading the way towards a cashless economy. 💻
#9YearsOfTechForGrowth#9YearsOfSeva
Empowering street vendors for a brighter future!
PM SVANidhi is transforming lives & livelihoods, providing financial support, & fostering entrepreneurship among street vendors in India
#9YearsOfGaribKalyan#9YearsOfSeva
Check out this captivating snapshot showcasing the incredible strides made in environment and sustainability during the 9 years of the Modi government.
#9YearsOfSustainableGrowth#9YearsOfSeva