Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#from#beautiful
A mother and a child on a wooden horse photo, in the style of gritty urban realism, new american documentary photography, mixed media installations, cheyenne art, rural life depictions, colorized, suburban ennui capturer --ar 103:128 --v 6.0
✅pitpeterssen _Midjourney v6.0
🚀Boost this Channel
@ai_artz🌿
#from#beautiful
Beautiful indian woman flying up in the sky with her aircraft chair, clouds moving in full speed, woman streching her hands on clouds, her hair also flying in speed, minimal, shot with Sony Alpha with wide angle lens, 16k, candid, aperture F1.2, full detail shot, dramatic lighting, --ar 16:9
✅ Vinaysaya _Discord
@ai_artz
#from#beautiful
Portrait and fashion photography: a combination of renaissance costumes and snowflakes, texturing, ::elegant clothes worn by the most beautiful women, a woman with a wonderful face and expressive eyes, beautiful delicate makeup, the highest quality, translucent floral fabrics, simple and aesthetic hairstyles, dynamic poses, neutral interesting dark background, award winning fashion photography, photorealistic, bright, elegant, golden ratio, elite, highly detailed, color triad, dynamic composition, ultra resolution, ultra wide shot, digital art, world made of light, soft lighting, unreal engine, depth of field 8k, full hd photo, HDR, high resolution photography, macro photography, beautiful highlights, zbrush art, photoshop, studio setting, simple, neutral, grainy, matte, fashion style :: Canon EOS 5D Mark IV EFL 100mm, f /1.4, ISO 50, 1/100 sec, Eye Sharpness, RAW, v4 - a r 2:3 - 800 sec, Chaos 49
✅ Adora _Discord
@ai_artz
#from#beautiful
An underwater urbex guerilla garden with old cars on the shoal underwater ::directional light, cinematic, alcohol ink and cinematic, saudek and sorayama ::hyperrealistic --ar 3:2 --q 2 --upbeta --s 750 --v 5.1
✅ Prima Demonessa _Discord
Join us for more @ai_artz
#from#beautiful
Gouache painting of a book-nook diorama of a cryptid conservatory, has incredible attention to detail, intricate, highly detailed, fantastic realism, fantasy, magical, led lights, --q 2 --s 750
✅ Adriann _Discord
@ai_artz
#from#beautiful
Photography of the living room of a huge hotel on Mars, futuristic Hotel on Mars furnished in japanes style, 8k, photo realistic, beautiful japanese design, welcoming Hotel, ultra realistic, ultra detaile
✅ Max05 _Discord
@ai_artz