Функция 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
#FARM/USDT analysis :
#FARM is currently in an uptrend, exhibiting a series of higher highs (HHs) and higher lows (HLs). The price is presently consolidating above the 200-period exponential moving average (EMA), and a bounce is anticipated, which would support the continuation of its bullish momentum. For a long entry, it is advisable to wait for a breakout above the $53 level to confirm the upward movement.
TF : 1H
Entry : $53.00
Target : $66.00
SL : $47.50
⚠️ Осторожно: после этого AMA может внезапно потянуть в #stake, #lend и #farm.
@bemofinance + @evaaprotocol + @bidask = 🔥
Увидимся завтра в 08:00 UTC! 👀
⚡️Electra meets you
The first DEX to trade perp assets directly from your wallet with high leverage, deep liquidity and the lowest fees.
Warm up with Bulls'n'Bears Game — pump $BTC to 1 billion, rack up points, and bring in more frens-electrons.
⭐️ More points mean bigger rewards!
⚡️Join Electra now!⏺
#TON#DEX#trade#farm#BTC
🤑Blum has released update — now we have the opportunity to create a tribe!
⚫️Go to tribe
⚫️ Every 8 hours we press “Claim”
⚫️ If possible, we spend tickets, because there was information that after a while they will expire
Also recently added the function of connecting a wallet and unlimited invites
♾
🛖Join our tribe and farm points for
💵 10% faster, as usual, let's try to reach the top together!
#blum#tribe#ton#farm
😸Farm $CATI on🎰🎰🎰
Today, 2 new farming pools with impressive prize pools appeared on the STON.fi exchange:
💎CATI/TON: 10,000 STON ($43,000)
🪙CATI/USDT: 10,000 STON ($43,000)
🗓 Farming will last until October 4. There is no blocking of LP tokens.
How to get rewards?
1. Top up the liquidity pool and receive your LP tokens
2. Click Farm on your liquidity pool
You can find detailed instructions here or watch our video guide📹
Farming is the process of earning rewards for providing your cryptocurrency as liquidity to decentralized finance platforms #DeFi.
#catizen#farm#stonfi#DEX#CATI
Raffle-airdrop $THNG from Drop Hunter and a mini-review of the token
😀 Things Token plans to launch an RWA platform for buying and selling real assets. It is hosted on our 🪙#TON blockchain and is already available on DEX platforms. You can learn more about the project.
The conditions for the #Airdrop are below:
🟡Launch the bot.
🟡Subscribe to the channel.
🟡Invite 5 friends (old referrals count).
🟡Buy 1 ticket and wait for the results to be announced.
Two-tier token system:
➖$THNGP: A token with voting rights in the DAO, mined through mining and participation in the presale. Can be exchanged for 👁#THNG at a ratio of 1:10. The transfer of this token is limited to a single transaction (for example, if you need to change your wallet). It can only be freely sent and received through mining, voting, and exchange (conversion) smart contracts. Do not attempt to sell these tokens or transfer them to exchanges.
😀$THNG: A freely tradable token for trading, transferring and other purposes.
🟡Drop type - Raffle.
🟡Total volume - 28 million $THNG coins
🟡Total winners - 400 people.
🟡For each user – $65,000 THNG for 1 ticket (50,000 points = 1 ticket)
😀 At the moment, THNG 2.0 staking is available with an APR of ~ 160% from August 23 to September 24.
🔥Keep farming and participate in all activities of DropHunters
#farm#drop#TON#web3