Функция 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
🟩Let's Share $150,000 in ZETA! zetablockchain
🎯Ready for an immersive experience with #ZetaChain Testnet before the mainnet launch and a chance for potential airdrops?
JOIN NOW 👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/ Galxe 👉https://galxe.com/TokenPocket/campaign/GCc28ttYTk
With such incredible projects, the anticipation for the #ZetaChain mainnet is booming! zetaswapdex LENX_Finance zkme_ UltiverseDAO SushiSwap ChatGM_Official CharacterXAI sugar_datingfi eddy_protocol TokenPocket_TP
【Details】https://twitter.com/TokenPocket_TP/status/1746790100393206137
【Powered By】Crypto Box
🆕 ZetaChain Testnet is Now Live on TokenPocket! zetablockchain
▶️Supported by TokenPocket Mobile Wallet and Chrome Extension Wallet!
TokenPocket now supports users to
✅ Custom add #ZetaChain Testnet to TokenPocket.
✅ Create & Import #ZetaChain wallets.
✅ Interact with #ZetaChain Testnet-based DApps.
🚀 Create your first #ZetaChain wallet on TokenPocket_TP!
Use Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/zetachain-testnet
👉https://www.tokenpocket.pro/
👉https://extension.tokenpocket.pro/#/
【Details】https://twitter.com/TokenPocket_TP/status/1704418412582338967
【Powered By】Crypto Box
🆕#ZetaChain is now live on TokenPocket_TP. zetablockchain
💚ZetaChain is a simple, fast, and secure Omnichain Blockchain.
🚀How to create/import a #ZetaChain wallet on #TokenPocket Mobile Wallet and Chrome Extension Wallet?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/zetachain
Download #TokenPocket
👉https://www.tokenpocket.pro/
👉https://extension.tokenpocket.pro/
#ZetaChain#TokenPocket $ZETA
【Details】https://twitter.com/TokenPocket_TP/status/1752905240133996845
【Powered By】Crypto Box
💥@zetablockchain Ecosystem is booming!!
💚You won't want to miss a chance to share 1,000 #ZETA, right? Dive into👇
https://galxe.com/TokenPocket/campaign/GCEZRtwWpG
🎯How to create & import a #ZetaChain wallet on TokenPocket_TP?
Full guide👇
(For mobile and Chrome extension users.)
【Details】https://twitter.com/TokenPocket_TP/status/1753242729960628260
【Powered By】Crypto Box
💥We’re excited to announce that #TokenPocketChristmas winners can claim rewards at
@ZetaBlockchain
mainnet launch! #ZetaChain
Check if you are on the first-round winner list
👉https://docs.google.com/spreadsheets/d/1zqZx0BHE0gVBn8doFhRAdFBaQrwoxzPbwu2CYCOkvhs/edit#gid=0
How to claim your #ZETA?
1️⃣Download TokenPocket Wallet
👉https://tokenpocket.pro
👉https://extension.tokenpocket.pro
2️⃣Create/import/sync your #ZetaChain wallet on TokenPocket after mainnet launch!
3️⃣Share the news with your friends if you are on the winner list! (RT, Like, Comment) 👉https://twitter.com/TokenPocket_TP/status/1752147092942749951
When to get your ZETA?
⏰The rewards will be distributed at the same time of #ZetaChain airdrop claim opens this week.
All participating user data from #TokenPocket are also whitelisted to get a boost in the first XP campaign on ZetaHub. Learn more about the 10% of the total ZETA token supply for community rewards: https://twitter.com/zetablockchain/status/1750758520637804707
AI Agent Launchpad Goes Live
Zearn launches the world’s first Universal AI Agent launchpad using autonomous AI on ZetaChain’s infrastructure. Users can create meme narratives and deploy AI agents in just three clicks, leveraging real-time social sentiment for refinement. Read more here.
Additionally, Utah's Bitcoin reserve bill has passed the Senate Revenue and Taxation Committee, marking a significant step for cryptocurrency regulation in the state.
#AI#Crypto#Zearn#ZetaChain#Bitcoin#Blockchain#Utah#Innovation
Quoted TokenPocket_TP : 💥All the #TokenPocketChristmas rewards have been distributed to winners' TokenPocket #ZetaChain Wallet!! #HODL
To celebrate the #ZetaChain Mainnet launched, TokenPocket provides 1,000 #ZETA to #TokenPocket users!
Dive into👇
https://galxe.com/TokenPocket/campaign/GCEZRtwWpG#ZetaChain
😁Eligible for TokenPocket users, please create/import a #ZetaChain wallet on #TokenPocket Mobile Wallet and Chrome Extension Wallet?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/zetachain
【Details】https://twitter.com/TokenPocket_TP/status/1752914758746210773
【Powered By】Crypto Box