Функция 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
⚡️Tether kompaniyasi Neuralink chiplariga o‘xshash texnologiya ustida ishlamoqda
⚡️ Tether kompaniyasi BrainOS deb nomlangan tizimni ishlab chiqayotganini e’lon qildi. Bu tizim inson aqlini sun’iy intellektning hisoblash imkoniyatlari bilan birlashtirishi mumkin.
⚡️ Kompaniyaning bashoratiga ko‘ra, yaqin 5–10 yil ichida sun’iy intellekt ko‘plab kasblarning ajralmas qismiga aylanadi va odamlar bunga moslashishga majbur bo‘ladi.
⚡️BrainOS bu muammoni hal qilish uchun taklif etilgan — texnologiyalarni to‘g‘ridan-to‘g‘ri inson miyasi bilan integratsiya qilish. Bu orqali fikrlash jarayoni tezlashadi va insoniyat sun’iy intellekt davrida yetakchilikni saqlab qolishi mumkin.
👉Bizning barcha loyihalar | #tether
CEO of #Tether warns about the possibility of mass mailing of phishing emails with the distribution of crypts
Hackers have hacked a "well-known" service provider for email newsletters (the name is not disclosed)
New investments by #Tether💵
Tether has invested $200 million in the biotech company Blackrock Neurotech, with a Brain-Computer-Interface (chipping, etc.. it looks like a Neuralink Mask)
Against the background of such investments by Blackrock Neurotech, Tether introduced its new division Tether Evo. The division will be engaged in investing in "human-oriented" technologies.
Earlier, Tether announced a new concept for the company, and also stated that they would invest in various areas of the global economy.
It is worth noting that Blackrock Neurotech has nothing to do with the Blackrock we know.
In general, biotechnology is an interesting investment direction, and Tether only confirms this + such movements pull the company beyond the framework of stablecoins.
Euro #Tether (EUR₮) and #Tether Gold (XAU₮) To Launch on BitMart Exchange
https://tether.to/en/euro-tether-eurt-and-tether-gold-xaut-to-launch-on-bitmart-exchange/
Euro #Tether (EURT) and #Tether Gold (XAUT) To Launch on SimpleSwap
https://tether.to/en/euro-tether-eurt-and-tether-gold-xaut-to-launch-on-simpleswap/