Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Мир продолжает понемногу отходить от массового зеленого умопомрачения. General Motors готовится представить новые двигатели V8, в разработку вложили почти $1 млрд.
Появится сразу два агрегата, 5,7 и 6,6 литра. Первый для таких моделей, как Chevrolet Silverado 1500. Второй – для ряда Corvette. Обещают, что они будут не простыми большими, а большими и технологичными.
По крайней мере в США выбор не будет ограничен перекрученными 2-х литровыми моторами.
#v8
🚗✨Maserati Unveils the Final Quattroporte with V8 – Grand Finale!🎉
This stunning vehicle, custom-made for a client in the USA, showcases a unique and exquisite design. 🌟🇺🇸 With the V8 engine now retired from the lineup, including the Ghibli sedan and Levante SUV, this masterpiece marks the end of an era.
A true symbol of luxury and performance! 🏁💎
#Maserati#Quattroporte#V8#GrandFinale#LuxuryCars#Auto🚘💖
🚗💨 Exciting news from Lamborghini! The upcoming Lamborghini Temerario is set to unleash over 1000 horsepower! 🔥
Ruwen Mor, a former Audi engineer now at Lamborghini, revealed that the power of the V8 engine could increase from 200 to around 220 hp per liter. Plus, the car will feature three electric motors for an extra boost! ⚡️
The Temerario follows in the footsteps of the iconic Huracan, which had a naturally aspirated V10 engine with a peak output of 640 hp. While a V6 could have delivered even more power, the decision was made to stick with a higher cylinder count to meet customer expectations. 💪
#Lamborghini#Temerario#Supercar#1000HP#V8#ElectricPower#CarEnthusiast#LuxuryCars#Auto