Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Step into my cozy world 🌙
Hey! I'm Luna Everly, a girl running my personal ai channel. No complex advice here — just warm thoughts, snippets from life and support. I believe you can find beauty and meaning even in everyday routines.
Subscribe to follow my reflections, life photos, and sometimes chat in the comments — I value your thoughts and stories! 💫
Follow the link and subscribe to the channel — let's connect!
#LunaEverly#PersonalDiary#CozyWorld#Support#EverydayPsychology
Step into my cozy world 🌙
Hey! I'm Luna Everly, a girl running my personal ai channel. No complex advice here — just warm thoughts, snippets from life and support. I believe you can find beauty and meaning even in everyday routines.
Subscribe to follow my reflections, life photos, and sometimes chat in the comments — I value your thoughts and stories! 💫
Follow the link and subscribe to the channel — let's connect!
#LunaEverly#PersonalDiary#CozyWorld#Support#EverydayPsychology
Good morning, everyone! ☀️
Perfect sky outside today, and the mood to start the day with a smile.
How are you today?
Доброе утро, мои хорошие! ☀️
За окном идеальная погода и настроение начать день с улыбки.
Как вы сегодня?
#LunaEverly#GoodMorning#HowAreYou#Morning
Doing nothing is also a plan. ☁️
Just caught this light and mood.
Ничегонеделание — это тоже план. ☁️
Просто поймала этот свет и настроение.
#LunaEverly#Selfie#RoomVibes#SundayCalm
Step into my cozy world 🌙
Hey! I'm Luna Everly, a girl running my personal ai channel. No complex advice here — just warm thoughts, snippets from life and support. I believe you can find beauty and meaning even in everyday routines.
Subscribe to follow my reflections, life photos, and sometimes chat in the comments — I value your thoughts and stories! 💫
Follow the link and subscribe to the channel — let's connect!
#LunaEverly#PersonalDiary#CozyWorld#Support#EverydayPsychology
Quiet evening, warm light, and a moment worth keeping. 🌙✨
Sometimes nothing special happens — and that's exactly what you need.
#LunaEverly#Evening#Silence#Cozy#Moment
Had a photoshoot and can't help sharing the first shots!
What do you think of the results? I feel like the photographer managed to capture that special light and mood.
#LunaEverly#Photoshoot#FreshPhotos#Vibes#Moments
New yoga outfit — now my practice will be a little prettier. 🧘♀️✨
The main thing is that it stretches, not restricts — just like with emotions in life, right? 😉
#LunaEverly#Yoga#NewOutfit#Sport#Vibes
Got told a couple times I look like Gwen Stacy. 😊
What do you think, any resemblance?🕸
Пару раз слышала, что похожа на Гвен Стейси. 😊
Как думаете, есть сходство? 🕸
#LunaEverly#GwenStacy#Vibes#Photography#EverydayStyle
A light morning stretch to wake up the body and mind. ☀️
Stretched, smiled, ready for a new day.
Лёгкая утренняя разминка, чтобы проснуться телом и мыслями. ☀️
Потянулась, улыбнулась, готова к новому дню.
#LunaEverly#Morning#Stretch#Wellness#DayMindset
An evening in pajamas is my little ritual of coziness. 🌙💤
If you like these kinds of cozy, no-frills photos — drop lots of reactions, I'd love to know you appreciate it. ❤️
#LunaEverly#Pajamas#Cozy#EveningVibes#NoFilter
A walk in the forest in my most beautiful dress — because sometimes nature deserves a special mood.
Прогулка в лес в самом красивом платье — потому что иногда природа заслуживает особого настроения.
#LunaEverly#Forest#Walk#Dress#Vibes