Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> text = '''
>>> Alex:8999123456
>>> Mike:+799987654
>>> Oleg:+344456789
>>> '''
Соответственно, для выделения нужных элементов будем использовать группы. Получится такой паттерн:
(\w+):([\d+]+)
Как мы будем формировать словарь из найденных групп?
>>> import re
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append({
>>> "name": match.group(1),
>>> "phone": match.group(2)
>>> })
>>> print(results)
[{'name': 'Alex', 'phone': '8999123456'}, ...]
Можно немного сократить запись используя zip
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append(dict(zip(['name', 'phone'], match.groups())))
Но есть способ лучше! Это именованные группы в regex. Можно в паттерне указать имя группы и результат сразу забрать в виде словаря.
>>> for match in re.finditer(r"(?P<name>\w+):(?P<phone>[\d+]+)", text):
>>> results.append(match.groupdict())
То есть всё что я сделал, это добавил в начале группы (внутри сбокочек) такую запись:
(?P<group-name>...)
Теперь найденная группа имеет имя и можно обратиться к ней как к элементу списка
>>> name = match['name']
Либо забрать сразу весь словарь методом groupdict()
>>> match.groupdict()
#tricks#regex
🚀🚀 75% Profit on #DMC/USDT for our Premium Members on Binance Futures/Bybit/OKXX/Kucoin/Bitget
✅✅ All target completed - Trade Closed
👁🗨Contact @primemod to enter the Premium Group for high quality SPOT & FUTURES Signals
🚗DeLorean (DMC) Reward Pool on Bitget
🔥 June 24, 2025, 7:00 PM – June 26, 2025, 7:00 PM (UTC+8)
During the event, stake your BGB or DMC tokens and share 66,176,000 DMC in rewards!
About the $DMC project by DeLorean:
1️⃣Strategic Partnerships:DeLorean Labs is collaborating with the Sui Foundation and Mysten Labs, leveraging Sui’s high throughput to enable lightning-fast transactions
⚡️
2️⃣ Brand Power: The iconic Back to the Future car meets Web3 — a nostalgic and compelling mix for fans and blockchain enthusiasts alike.
3️⃣Real-World Utility: Use $DMC to purchase the
🚗DeLorean Alpha 5 EV, limited editions, and exclusive merchandise. Future plans include luxury goods and expanded payment use cases.
4️⃣NFT Ecosystem: $DMC powers the DeLorean Labs marketplace — enabling collecting, reselling, and interactive experiences.
5️⃣Decentralized Governance: Holders of $DMC can vote on features, partnerships, and the future direction of the community.
🔌How to Join
➡️ Visit the staking page
➡️ Choose the $BGB or $DMC pool
➡️ Start staking and earn rewards 💵
Hop into the pool — and ride the crypto car of the future!
#BackToTheFuture#web3#DMC
Я так просто Саше не сдамся - тем временем я делаю уже Данте для другой студии 🌚
Видимо, теперь тоже придётся вставать в 4.30 утра
Только лишь из принципа, правда?..
#kolori#анонс#dmc
📊Сообщество MICE Backstage опубликовало анализ своих участников!
Мы провели исследование, чтобы выяснить, кто входит в наше сообщество, из каких стран они происходят, и каково процентное соотношение мужчин и женщин среди участников. Особое внимание уделили представителям компаний, активно участвующих в жизни сообщества.
Интересные факты из исследования:
- Представители компаний, работающих исключительно в сфере MICE, составляют 41,9%.
- Представители DMC — 13,6%.
- Корпоративные клиенты — 2,3%.
- Event & MICE специалисты — 12,8%.
- Представительство по маркетингу 4,9%
📊Больше данных и подробности на нашей инфографике!
#MICE#MICEBackstage#АнализСообщества#СобытийныйМаркетинг#DMC#EventManagement
🚗💨 Exciting news from the German tuning atelier DMC! They've unveiled the first tuning kit for the stunning Lamborghini Revuelto! 🌟
This incredible kit features:
✨ Two different rear wings
✨ An alternative diffuser
✨ Side skirt overlays
✨ New side mirror housings
The stock V12 engine delivers a jaw-dropping 1015 horsepower, but with DMC's modifications to the exhaust system and engine control unit, it now boasts an impressive 1099 horsepower! 🔥💪
And here's a twist: all parts from the kit will be available for purchase exclusively in Bitcoin! 💰💻
#Lamborghini#Revuelto#DMC#Tuning#Supercar#V12#Performance#Bitcoin#LuxuryCars#Auto