Функция 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
Lookonchain | ꘜ
BTC just broke through $124,000, setting a new all-time high!
If you bought #Bitcoin every day like the El Salvador government, you'd have a 115% return!
Since Nov 18, 2022, El Salvador has been buying 1 $BTC per day — buying 1,000 $BTC(cost $57.29M, now worth $124M) at an average price of $57,793, with an unrealized profit of $66M(+115%).
https://intel.arkm.com/explorer/entity/el-salvador
An Satoshi-era #Bitcoin OG moved 1,000 $BTC worth $74.03M to 2 newly created wallets and is likely preparing to sell.
The wallet still holds 1,833 $BTC worth $135.6M.
https://intel.arkm.com/explorer/address/bc1qczar85zjppfjr8df8qnc4l3h5r957v6p2udryz
https://x.com/OnchainLens/status/2044355669982380083
Follow @OnchainLens for more Onchain Updates.
Erik Voorhees(@ErikVoorhees), an early #Bitcoin supporter and founder of ShapeShift, is buying back $ETH after a one-year break.
One year ago, he sold 12,886 $ETH($42.83M) at $3,324.
In the past 5 days, he has spent 17.75M $USDT to buy back 8,576 $ETH at $2,069.
He still holds 26.77M $USDT and may buy more $ETH.
https://intel.arkm.com/explorer/address/0x431dcE06f8A098C6f70CA6CecdCa87281eF10c91
Charles Schwab increased his position in the financial company Strategy $MSTR of #Bitcoin by 91,559 to 1.27 million shares ($168 million).
Charles Schwab, who oversees trillions in client assets, increased his position in Strategy ($MSTR) by 91,859 shares, raising his total holdings to 1.27 million shares worth around $168 million.
Strategy is widely known for its large Bitcoin treasury strategy, making MSTR an important proxy vehicle for institutional engagement in Bitcoin via traditional stock markets.
Analysts say that Schwab's increased allocation reflects the ongoing institutional confidence in Bitcoin-related stocks and reinforces a deeper integration between traditional finance and digital asset-based corporate strategies.
🥳@Runlifenick_fx✅
🐱🙏🐶🚨
Michael Saylor says, “You’ve got 10 years for the digital gold rush, you should get your #Bitcoin before there’s no more Bitcoin for you.” 🤯
🌍t.me/Runlifenick_fx✅
BULLISH: 🟠 Billionaire Michael Saylor says $1 million #Bitcoin price is inevitable.
“It will grow from $2 trillion to 20 trillion to $200 trillion” 🚀
Source: @Runlifenick_fx✅