Функция 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
🔎Telegram May Be Quietly Testing a Feed like Feature
Telegram has recently introduced a new ‘Posts’ tab in Search, allowing users to easily discover content from public channels. This update comes roughly a year after the launch of #hashtagsearch, signaling Telegram’s continued focus on improving content discoverability.
This appears to be a soft launch of a potential future ‘Feed’ feature — offering users a scrollable stream of relevant #posts, possibly influenced by engagement metrics such as stars.
If fully implemented, this feature could significantly boost post visibility for channels, increase ad exposure for advertisers, and enhance ad revenue opportunities for creators. All indications suggest that Telegram is gearing up to roll out a #feed-based content experience, a move that could reshape how users browse and interact on the platform.
When the chat reaches 4,000 members or the channel 90,000, 10 group members will be allowed to create a post each, about a sfw topic of their own chosing. You must give @googlefactss permission to use your post and add it to the channel, with or without your username.
More details will come after we hit these numbers. Invite friends, family, and coworkers to join.
Do not spam/send links without permission of the place you send them in!!
Our group links are:
Main channel https://t.me/googlefactss
Group:
https://t.me/googlefactssgroup
@googlefactss📢👥
#Community#Permission#Posts#Growth#KeepTrackOfThisPost
@channely_bot
Qué puede hacer este bot?
Este bot es el mejor asistente para la gestión de canales en Telegram. Conecto los canales al servicio principal. ¡Incluyendo un rico entorno webUI de edición!
https://app.channely.co/
Idioma: Inglés
(visto en @BotsGram.cu)
#canales, #canal, #gestión, # administración, #richeditor, #posts, #schedule, #polls, #comment, #commenting, #reactions, #editor, #share, #buttons, #webui, #subscribe, #stats, #users, #trial, #limited, #proaccount