Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
📍 Kruger National Park, South Africa 🇿🇦
🦁 Kruger National Park is one of the most famous safari destinations in the world. It is home to Africa's "Big Five": lions, elephants, buffalo, rhinos, and leopards 🐘. The vast area of the park allows you to see wild animals in their natural habitat, and the diverse landscapes, from savannas to forests, make every trip unforgettable. 🌿
🚗 Tourists can explore the park by car or go on an organized safari with guides. Exciting sunsets, rare bird species, and the opportunity to see African life up close make this place a true adventure. The park is open year-round and ready to give bright emotions to every visitor! 🦓
#travel#safari#wildlife
safari
noun
uk /səˈfɑː.ri/ us /səˈfɑːr.i/
an organized journey to look at, or sometimes hunt, wild animals, especially in Africa.
[Source] 🐒🦒🦏
@googlefactss
#Africa#safari