Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Ладно, уже только за это взаимодействие можно порекомендовать сообщество дизайнеров Ньюс в телеграме, которое организовал Женя Арутюнов с командой
Продающий лендос с манифестом и промокодами тут
Если что, это ребята, которые когда-то для Додо придумывали смищные фразочки и другие оч человечные взаимодейтсвия)
🎤Ссылки на утро — второй канал
⏲Устойчивый VPN за звезду
#interaction@cogload#copywriting@cogload
🪐 The galaxy Arp 273, located about 300 million light-years away in the constellation Andromeda, is an extraordinary pair of interacting galaxies twisted into a shape that looks like a cosmic rose. One galaxy’s gravity is pulling and warping the other’s spiral arms, creating elegant loops and arcs that reveal the dramatic effects of galactic encounters in deep space. ✨
#galaxies⚡#interaction⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🌍 The geographic shell of the Earth is where the land, water, air, and life all meet and interact. This thin, dynamic layer makes our planet uniquely suited for life to thrive. ✨
#geography⚡#earthshell⚡#interaction⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In Japan, centuries-old forest areas called satoyama are shaped by human care for farming, wood, and water, blending wild nature and villages into landscapes rich in biodiversity and tradition. ✨
#interaction⚡#landscapes⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Indonesia, ancient forests and rice terraces share land with villages, blending wild and human-shaped environments. This mix supports rare wildlife while feeding local communities. ✨
#interaction⚡#landscapes⚡#sustainability⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the Swiss Alps, ancient irrigation channels called "bisses" direct mountain water through villages and fields. These hand-built waterways have shaped both local ecosystems and farming for centuries. ✨
#interaction⚡#society⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels