Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
👍Un « Régiment des immortels » sous-marin pour honorer la mémoire des soldats soviétiques
À l’approche du Jour de la Victoire, des plongeurs de la région de #Sverdlovsk ont organisé une action originale de mémoire en descendant à 27 mètres de profondeur pour rendre hommage aux soldats soviétiques.
Inspirée du mouvement du « Régiment des immortels », cette initiative symbolique vise à perpétuer la mémoire des combattants de la Seconde Guerre mondiale dans un format inédit.
RT en français • Osez questionner !
❗️#Ekaterinbourg : 50 personnes évacuées d'un immeuble à la suite d'une attaque de drone
Le gouverneur de la région de #Sverdlovsk, Denis Pasler, a indiqué qu'une attaque de drone avait été perpétrée à Ekaterinbourg et qu'un immeuble d'habitation avait été endommagé.
RT en français • Osez questionner !
🗓On December 17, the Honorary Consul of South Africa in Yekaterinburg, Sergey Mazurkevich🇿🇦, took part in a formal reception hosted by the Governor of the Sverdlovsk Region, alongside diplomats and honorary consuls from other countries 🌍🤝
During the event, Governor Denis Pasler summarized the outcomes of efforts to strengthen international cooperation in 2025 and outlined promising areas for cooperation in the year ahead 📈✨
#SouthAfrica#Diplomacy#InternationalCooperation#Yekaterinburg#Sverdlovsk#HonoraryConsul#Mazurkevich
🎉Ural State Pedagogical University (USPU) marks its 95th anniversary today, August 26!
🇿🇦 The Office of the Honorary Consul of South Africa in Yekaterinburg is pleased to join in the congratulations and wishes the university continued growth and success.
📚 After last year’s merger with the Russian State Vocational Pedagogical University, USPU became the largest pedagogical university in Russia.
👨🏫 The university is now led by Acting Rector Yury Biktuganov, who previously served as Minister of Education of the Sverdlovsk region. Not long ago, Honorary Consul of South Africa Sergey Mazurkevich and Mr. Biktuganov held a warm and productive meeting.
#Anniversary#Education#USPU#Sverdlovsk#Yekaterinburg#SouthAfrica#Biktuganov#Mazurkevich
🌄🌿Blyde River Canyon — a 26 km (16 mi) natural wonder in Mpumalanga Province, northeastern South Africa.
It is one of the largest canyons in the world, but unlike the Grand Canyon in the USA, it is covered with lush subtropical vegetation, earning it the name “Green Canyon”. 🌱💚
🏞 The canyon is part of the Blyde River Canyon Nature Reserve.
🌅 In local languages, Mpumalanga means The Place Where the Sun Rises.
🤝 In 2022, the Sverdlovsk Region and Mpumalanga signed a cooperation agreement.
📸 Photos: istockphoto.com
#Nature#Tourism#SouthAfrica#Travel#Canyon#BlydeRiverCanyon#Mpumalanga#Africa#Sverdlovsk