Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
"I'm rose without it's essence,
I'm a bouquet of autumn leaves,
I'm a tree without it's texture,
I'm glass without it's fragility,
I'm a sidewalk without grafitti,
A plain white coral,
I'm a scenery without a painter,
You see;
I still exist without you,
But It's not beautiful..."
#review#nilu
🔥 Дизайнер Александр Селипанов, основавший автомобильный бренд Nilu27, рассекретил суперкар Nilu
Интерьер — смесь минимализма и футуризма. Физических кнопок практически нет — лишь на потолке имеются переключатели в авиационном стиле. При этом тачскринов в салоне суперкара тоже нет: единственный дисплей встроен в зеркало заднего вида.
Базируется автомобиль на углепластиковом монококе с трубчатыми подрамниками, имеет полностью независимую подвеску и 21-дюймовые колёсные диски с карбон-керамическими тормозами Brembo с шестипоршневыми суппортами.
Атмосферный 6,5-литровый V12 развивает 1070 л.с. и 860 Нм, что позволяет разгоняться до максимальных 400 км/ч и набирать первую сотню быстрее чем за 3 секунды.
Полноценная премьера состоится 15 августа. Сначала сделают 15 машин для гоночных трасс, а уже потом выпустят 54 купе для дорог общего пользования.
@avtoNovosti
#новинки#суперкар#Nilu
🔥 Designer Alexander Selipanov, who founded the car brand Nilu27, has declassified the Nilu supercar
The interior is a mix of minimalism and futurism. There are practically no physical buttons - only on the ceiling there are switches in aviation style. At the same time, there are no touchscreens in the interior of the supercar either: the only display is built into the rearview mirror.
The car is based on a carbon fiber monocoque with tubular subframes, has a fully independent suspension and 21-inch wheels with Brembo carbon-ceramic brakes with six-piston calipers.
Atmospheric 6.5-liter V12 develops 1070 hp and 860 Nm, which allows to accelerate to a maximum of 400 km/h and gain the first hundred faster than 3 seconds.
The full-fledged premiere will take place on August 15. First, 15 cars will be made for race tracks, and then 54 coupes for public roads will be released.
@CarsNews
#new#supercar#Nilu
🚗✨Introducing the Nilu Supercar by Alexander Selipanov!🔥
Designed for true driving enthusiasts, the Nilu is a masterpiece that strips away unnecessary electronics to deliver pure driving pleasure. 🏁💨
🔩Powerful Performance:
Equipped with a breathtaking atmospheric V12 engine producing 1070 hp, paired with a 7-speed manual transmission. This beast can reach a top speed of 400 km/h and accelerate from 0 to 100 km/h in under 3 seconds! ⚡️
⚙️Cutting-Edge Engineering:
Built on a carbon fiber monocoque with tubular subframes, featuring fully independent pushrod suspension and 21-inch wheels with carbon-ceramic brakes. 🛠️
🚢Exclusive Release:
Only 15 units will be produced for track enthusiasts, followed by another 54 road-ready models. Pricing details remain under wraps! 💰
#Nilu#Supercar#AlexanderSelipanov#DrivingPassion#V12#Auto