Функция 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
🔍 The theory that the current growth is driven by institutional investors was confirmed by analysts at Chainalysis. Based on their data:
▫️77% of the already mined and not lost bitcoins (14.8 million BTC) are stored in “illiquid” wallets, the growth was provided by traders and retail investors (since 2017, the increase was 3 million BTC).
▫️Such wallets are involved in large transfers between exchanges, which increased by 19% in 2020 compared to 2017.
▫️Wallets are associated with North American exchanges, as they are of higher priority for institutional traders in the US and Europe.
#opinion#Chainalysis
🏦CEO Chainalysis прогнозирует легализацию стейблкоинов в 2025 году
🟩 По мнению гендиректора Chainalysis Джонатана Левина, в 2025 году начнется ускоренная легализация стейблкоинов в США и других странах мира.
🟩 Левин отметил, что в 2024 году на американском рынке увеличился оборот биткоина благодаря запуску ETF. Однако оборот стейблкоинов в США сократился по сравнению с динамикой в других странах.
🟩 Если Конгресс США примет законопроект о легализации стейблкоинов, это станет поворотным моментом для рынка.
#Cтейблкоины#Chainalysis#Крипторынок
АкадемияGarantex|Garantex Announcements|ВКонтакте|YouTube
🚀 Chainalysis Predicts Stablecoin Volume Could Reach $1.5 Quadrillion by 2035
Chainalysis has projected that the adjusted stablecoin volume could reach $719 trillion by 2035 through organic growth. According to NS3.AI, this figure could approach $1.5 quadrillion if two catalysts come into play. Chainalysis noted that this ceiling-case scenario would surpass the current estimated $1 quadrillion in global cross-border payments.
#Stablecoin#Cryptocurrency#Blockchain#Finance#DigitalAssets#GlobalPayments#CryptoMarket#Chainalysis
🚀 Stablecoin Transaction Volume Projected to Surge by 2035
Chainalysis has projected a significant increase in the inflation-adjusted real economic transaction volume of stablecoins, estimating a rise from $28 trillion in 2025 to $719 trillion by 2035. According to NS3.AI, this growth could see stablecoin payment processing volumes reaching parity with Visa between 2031 and 2039.
#Stablecoin#TransactionVolume#Crypto#Blockchain#Finance#PaymentProcessing#Visa#EconomicGrowth#NS3AI#Chainalysis
🚀 Treasury Secretary Advocates for Clarity Act Amid Rising Stablecoin Transactions
Treasury Secretary Scott Bessent has called on Congress to approve the Clarity Act, highlighting the growing significance of stablecoin transactions. According to NS3.AI, a report by Chainalysis projects that stablecoin transaction volume could escalate to $1.5 quadrillion by 2035, up from $28 trillion last year. The likelihood of the bill passing this year has increased, with Polymarket odds rising to nearly 70% from 50% earlier this week. Senate Banking Committee members are reportedly preparing to hold a hearing to vote on the bill before the month's end.
#TreasurySecretary#ClarityAct#Stablecoin#StablecoinTransactions#ScottBessent#Congress#Chainalysis#Polymarket#SenateBankingCommittee#Blockchain#Cryptocurrency
FTX Set to Pay $16B to Creditors
🎄 FTX will start repaying $16 billion to creditors on January 3, 2025. Payments will be made in stablecoins over 60 days. A significant portion of these repayments could re-enter the market, potentially fueling growth.
🔗Source
#FTX#Crypto#Stablecoins#MarketGrowth#Creditors#Payments#Blockchain#Finance#Investing#Web3#DeFi#Chainalysis#NorthKorea#CryptoTheft #2024 #Investment#Economy#ECON#News
Chainalysis Acquires Alterya for $150M
Chainalysis has acquired AI security startup Alterya for $150 million. Alterya's AI technology helps detect and prevent fraud in crypto services. Notable clients include Coinbase, Square, and Binance.
Read more here: Business Insider
#Chainalysis#Alterya#AI#Crypto#Cybersecurity#FraudDetection#Coinbase#Square#Binance#Acquisition#TechNews#Blockchain#Innovation#DigitalAssets#Investment#MarketTrends#Security#Startups#DataAnalysis#Fintech#Economy#VC
Bitcoin Tax Fraud Case Sentenced
Texas resident Frank Richard Ahlgren III faces two years in prison for tax evasion linked to the sale of $4M in Bitcoin. Ordered to pay $1,095,031 in restitution, this marks the first purely crypto-related tax fraud case in the U.S. Ahlgren concealed transactions using multiple wallets and mixers like CoinJoin and Wasabi Wallet. Details: source
#Bitcoin#Crypto#TaxFraud#Blockchain#USA#Court#Restitution#Legal#Finance#Tax#CryptoRegulation#CryptoNews#Ahlgren#PeerToPeer#Wallets#Mixers#CoinJoin#WasabiWallet#Chainalysis#Investigation#Fraud