Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Лето в разгаре, и мы решили:
Почему бы не раздать то, что вы любите больше всего?
FRHT #GIVEAWAY
Разыгрываем 10 футболок из новой коллекции FRHT 🔥
Условие участия простое — Подписаться на этот канал 🏁
*если ещё не с нами
Мы случайным образом выберем 10 победителей и отправим выбранные футболки
Итоги 25 июля. Поехали 🚀
🎉Bitget Wallet x All At Once #Giveaway🎉
🕙Event duration: August 23 - August 30, 2024
💰Rewards:
🚀$3,000 worth of TON for 300 lucky participants🚀
5M xAAO prize pool is shared equally among all participants
How to join:
1️⃣ Follow @BitgetWallet + @AAO_Game
2️⃣ Join the AAO & Bitget Wallet Telegram groups:
3️⃣ Join the All At Once Bot and complete one game battle
4️⃣ Fill out the Google form to receive your reward
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
💝GAMEWTB Valentine's Day Giveaway - Steam Gift Card💝
Happy Valentine’s Day!💖 As a token of our appreciation for your continued support, the GAMEWTB TEAM has prepared a special gift🎁 for you.
💸Prize: $5 Steam Gift Card
📅FROM NOW - FEB 17, 2025
=How to Participate=
📲Follow our X: x.com/PC_Gamewtb
❤️♻️LIKE & RETWEET THIS POST☝️
⏰Winner will be announced on Feb 17th
✅COMMENT "DONE" UNDER THIS POST☝️
👀Wait our DM💌
Limited Time Event – Don’t Miss Out!
🤩Whether you're spending Valentine’s Day solo or with a special someone, remember to love yourself! GAMEWTB will keep bringing you the latest game news and exciting events.
Join Gamewtb Group for GIVEAWAYS!
#GIVEAWAY
💚🍀🌱 FARMERS, LISTEN UP! 💎✨
One of the LAST chances to grab OG role 🎖 and it’s about to go CRAZY 😤🔥
We're dropping a massive GIVEAWAY 🎁 /w 30 winners
EACH GETS 0.1 SOL 🤑 + OG 👑
How to join:
1. Join our X (Twitter)
https://x.com/ggpweb3
2. Join our Discord
https://discord.gg/gg-paradise
3. Leave wallet in #giveaway channel
4. Stay active on server
Results in Friday 🕶
Let’s make it loud before the farm goes wild 🌿🚀
💥500 QUACK AI NFTs and 200,000 QUACK Points Giveaway to TokenPocket users!
👉https://app.galxe.com/quest/TokenPocket/GC6YCtmDkS
🍾500 lucky winners will each receive a QUACK AI NFT!
🎯 Winners will also be eligible to earn an extra 400 points by interacting with the QUACK AI platform.
#giveaway
💧Airdrop : Lifestory💧
📣Complete Task: ➕ $6000 #Giveaway - 4 Days contest
🏆Winners: For All Valid Users
📅End date: After 4 Days
💎Ratings: ⭐️⭐️⭐️
🔛Galaxy Airdrop Gleam Click Here🔛
🌀 Follow on Twitter and retweet the pinned post.
🌀 After Done Airdrop Task then Create your wallet.
📡Enter your information to the Airdrop Gleam.
🗞Note: All airdrop steps should be completed.
⛵️Business Inquiry: Admin || Admin2
💥Big Congrats!
🏆Check if you are on the ZoomManor #Giveaway Winner List!
👉https://docs.google.com/spreadsheets/d/1QQ1rdc3jnt6BAhWL_8qhJJe56KyxSqF8BvCk21dLvSk/edit#gid=0
🎁The rewards will be distributed by ZoomManor before Jan 5th. ZoomManor
💙Thank you all very much for your participation!
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
🪂New airdrop: FOBOCLUB x MEXCGlobal Collab Event #giveaway
💰Reward: 50 FOBO CLUB WLs (NFT)
📅Distribution: uncertain
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🪂Airdrop: Mystery Box #Giveaway
💰Reward: $3,000
👨💼 Winner: All participants
📅 TIME:10/03/2022 07:00 AM - 10/09/2022 11:00 PM UTC
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!