Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Remember, Most of your stress comes from the way you respond, not the way life is.
Adjust your attitude. Change how you see things. Look for the good in all situations. Take the lesson and find new opportunities to grow. Let all the extra stress, worrying, and overthinking go.
#Inspirational
Prioritize your mental and spiritual wellness. Do things that make you happy. Take time to nurture yourself. Don’t rush the process. Don’t judge where you’re at or where you think you should be. Just be kind and patient with yourself. Things are unfolding for you.
#Inspirational
Wrinkles, scars, imperfections, strengths, & weaknesses - all these made you who you are today - a strong, independent, beautiful human being. Embrace it all with gratitude. When you learn to accept & love everything about you, nobody can ever use it against you.
#Inspirational
“I will love the light for it shows me the way, yet I will endure the darkness because it shows me the stars.”
🍃 Og Mandino
#uplifting#inspirational#motivation#life#wisdom
@quietworld🍃