Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
India's mobile manufacturing sector has come a long way!
Thanks to government initiatives like PLI, Make in India, and Digital India, India's tech sector is leading the way towards self-reliance. India is no longer dependent on mobile imports.
#MeriSarkar
#JanDhanYojana केवल बैंक खाते खोलने के बारे में नहीं है; बल्कि यह नई संभावनाओं का द्वार है और इसने करोड़ों महिला लाभार्थियों के जीवन को आसान बनाया है।
#MeriSarkar
Proud moment for India's mobile manufacturing industry!
The world is increasingly choosing Made in India mobiles, a testament to the country's quality and innovation in the tech sector.
#MeriSarkar
#PaiPaiSeDeshKiBhalai
Global giants have expanded their operations, showing immense confidence in India’s growth story. It has boosted job opportunities and paved the way for India’s digital transformation.
#MeriSarkar
#PaiPaiSeDeshKiBhalai
The world is recognising the success of Jan Dhan Yojana. India has become a global leader paving the way for financial inclusion at a massive scale and speed.
#MeriSarkar
#JanDhanYojana
In the most unprecedented circumstances like the Covid-19 pandemic, Rs 31,000 crore were directly transferred into the bank accounts of Jan Dhan Yojana women beneficiaries.
#MeriSarkar
#JanDhanYojana
Jan Dhan Yojana is not just about opening bank accounts; it is a door to new possibilities and has ensured ease of living for crores of women beneficiaries.
#MeriSarkar
#JanDhanYojana
India's mobile manufacturing sector is becoming #Aatmanirbhar!
PLI is driving growth in the mobile manufacturing sector, making India a leader in mobile production and creating new opportunities for domestic players.
#MeriSarkar