Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
🌍 Tropical peat swamp forests store massive amounts of carbon in deep, soggy soils. Some areas in Southeast Asia hold peat deposits over 10 meters thick, locking away centuries of trapped carbon. ✨
#rainforest⚡#carbon⚡#wetlands⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some freshwater wetlands and deltas trap so much carbon in their soil that, hectare for hectare, they store more than most forests—making them powerful natural climate regulators. ✨
#wetlands⚡#delta⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Arctic tundra’s permafrost acts like a giant freezer, locking away twice as much carbon as all the world’s forests combined, making it a crucial regulator for Earth’s climate. ✨
#permafrost⚡#tundra⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The global carbon cycle constantly moves carbon between the air, land, water, and living things. This cycle helps regulate Earth’s climate by storing and releasing carbon dioxide. ✨
#carbon⚡#climate⚡#cycles⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Canada holds more than 30% of the world’s forests, making it the top country for natural forest area. These forests store massive amounts of carbon and water—critical global natural resources. ✨
#resources⚡#forests⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Grand Power кобура скрытого ношения на быстросъёмных крепежах с мягким слоем Alcantara внутри.
Двойной подсумок
Кобура скрытого ношения с Alcantara, с дополнительным магазином.
➡️#grandpower
➡️#моноблок
➡️#carbon
НЕ ПРОДАЖА ОРУЖИЯ! ⚠️
Демонстрируется только для наглядности функционала.
По вопросам заказа связывайтесь с нами📱
ПОДПИСЫВАЙТЕСЬ ЧТО БЫ НЕ ТЕРЯТЬСЯ:
📱MAX
📱VK
@DP_KH
🌍 Some grassland soils are so fertile they can support crops for decades without added fertilizer. These deep, dark soils store huge amounts of carbon, helping stabilize the global climate. ✨
#grasslands⚡#soil⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Argentina’s Pampas are vast temperate grasslands that grow some of the world’s richest soils. These grasslands support massive cattle herds and store huge amounts of carbon underground. ✨
#grasslands⚡#pampas⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels