Функция 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
❓Do you want to build a #dApp on Venom❓
✅ Join the VenomBlockchain dev community on Discord
➡️https://discord.gg/E5JdCbFFW7
🔎 Check Venom docs with development guides for smartcontracts, tokens, NFT, and more
➡️https://docs.venom.foundation/build/development-guides
⚡️TON Community: MyTonWallet v3.6 Features Unveiled
#TON#Dapp
The TON Community introduces MyTonWallet v3.6 with significant updates. Users can now track any wallet address and view $TON activity within the app, and share transfer links before confirmation. Discover new features like Remember Passcode and Dapp Action Previews.
Source: link
@tonlines
🆕We just released TokenPocket's new version on iOS. 🔺2.4.8🔺
🔵Support Boost Mode. 🚀#memecoin
🔵Native support for #DApp Content Translation.
🔵Native support for TRON Batch Transfer.
You can now upgrade your TokenPocket on the App Store. Ensure the developer is 'TP Global Ltd'.
🔗https://tokenpocket.pro
🆘 Просто эпический фейл от WalletConnect, который я обнаружил сегодня утром.
#WalletConnect - крупнейший (и возможно единственный) сервис подключения крипто кошельков к #dapp#web3 приложениям внес Украину и РФ в черный список.
По сути это парализует работу всего DeFi для СНГ. Вот такая децентрализация или иначе - отсутствие альтернатив “не из США”!
🍌
30 million users in Bitget Wallet!🌐
Bitget Wallet is a cutting-edge Web3 multi-chain wallet that offers a comprehensive platform with wallet, exchange, NFT marketplace, DApp browser, and Launchpad features. Supporting over 100 public blockchains, Bitget Wallet aggregates top DEXs and NFT markets to provide users with the best trading prices.
Bitget Wallet's mission is to create a world-class decentralized crypto wallet that provides a secure and convenient trading experience for all crypto enthusiasts.
Since its founding in May 2018, Bitget Global Inc. has been providing secure asset storage, fast trading, exchange, and investment in DeFi to over 30 million users worldwide. Now it is not just a wallet but an entire ecosystem that provides access to various activities and airdrops.
Tomarket Airdrop
Bitget On Chain Fund Invests in Tomarket App, Fast-Growing Web3 Game on TON. Airdrop scheduled for September.
Join the farming and get 2,000 🍅 $TOMATO tokens at the start!
Download Bitget Walletand start your Web3 journey now!🚀💎
#BitgetWallet#Web3#NFT#TON#DApp#DEX
🆕 0xMantle Bridge now fully supports TokenPocket login, and the official bridge is also listed on the TokenPocket #Mantle Hot #DApp List!
👉https://bridge.mantle.xyz/
🔥You can access Mantle Bridge with your TokenPocket wallet and enjoy the #MantleJourney!
👉https://extension.tokenpocket.pro/#/
👉https://www.tokenpocket.pro/en/download/app
#TokenPocket#MantleJourney
【Details】https://twitter.com/TokenPocket_TP/status/1711686131371413918
【Powered By】Crypto Box
🆕 Mantle Bridge now fully supports TokenPocket login, and the official bridge is also listed on the TokenPocket #Mantle Hot #DApp List!
🔥You can access Mantle Bridge with your TokenPocket wallet and enjoy the #MantleJourney!
👉https://extension.tokenpocket.pro/#/
👉https://www.tokenpocket.pro/en/download/app
#TokenPocket#MantleJourney
【Details】https://twitter.com/TokenPocket_TP/status/1711685010049368156
【Powered By】Crypto Box
😼Catizen Mini Game Center Open Beta now LIVE!🚀🎮
👌 Dive into a world of top-tier games that blend fun with innovative earning opportunities. Enjoy exclusive rewards like game airdrops and referral bonuses.
👌 Earn a 10% top-up rebate from all your referrals across all games, including Catizen!
Don’t miss out — start your adventure in the Catizen Mini Game Center today! 🌟
🔡
🔡
🔡 Open beta is live! Report bugs or game feedback to earn 300 Catizen FishCoins 🪙
😸Explore Catizen Mini Game Center
#catizen#gamee#play#p2e#web3#gamefi#dogs#telegram#dapp#notcon#hamsetr