Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
परीक्षा से पहले की तैयारियों को लेकर अब बिल्कुल न हो परेशान; क्योंकि प्यारे बच्चों जल्द आ रहा है प्रधानमंत्री के साथ परीक्षा पे चर्चा 2023 संवाद।
#PPC2023
https://youtu.be/SKmrRc2-QTQ
अपने पैशन को चुनें या एक अच्छे करियर की प्लानिंग करें?
करियर या परीक्षा से जुड़े आपके सभी सवालों के पीएम 27 जनवरी 2023 को देंगे जवाब। #PPC2023
https://youtu.be/RzB7PY4VX0w
विजिट करें: mygov.in/ppc-2023/
परीक्षा से डरने के बजाय मुस्कुराते हुए उसे अपना बनाएं।
27 जनवरी, 2023 को #PPC2023 में प्रधानमंत्री के टिप्स से परीक्षा या करियर से जुड़े आपके हर सवाल का मिलेगा समाधान।
#PPC2023
👆Wondering how to create a perfect balance of studies and sports for your children during exams? PM Modi is here to help
Participate in #PPC2023 and get tips on dealing with your children's exam stress!
Visit: innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
परीक्षा के मुश्किल दिनों को बनाएं खुशनुमा और तनावमुक्त। परीक्षा पे चर्चा 2023 में शामिल होने के लिए भेजें अपने सुझाव और सवाल, आपको मिल सकता है प्रधानमंत्री से सीधे संवाद का मौका।
#PPC2023
https://youtu.be/YcV_uea2ok8
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Help your children reach their maximum potential this exam season, with PM Modi's inspiring advice!
👉 Participate in #PPC2023 and make your children exam ready.
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/