Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Andan muy salsas 🤔
🔴 Los legisladores de #MC pidieron que Rubén Rocha, Enrique Inzunza y Juan de Dios Gámez sean juzgados en México por presuntos vínculos con el CDS ☝🏻📄⚠️
https://revistaelpolitico.com/nacional/mc-pide-desafuero-y-juicio-politico-ruben-rocha/
📊#MC breakout the cup and handle pattern. Currently, it is retesting above it. MACD crossover is showing bullish momentum. 💎
A successful retest above the horizontal support would confirm the upward move, while a failed retest could lead to a downward movement.👀
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
📊#MC pumped with a high volume after the breakout of the lower marked horizontal resistance, which will now act as support. RSI is in the overbought region and it is getting rejected from the horizontal resistance.
📉
💬A solid breakout of the horizontal resistance would be the bullish confirmation, while in case of rejection, it will bounce from the horizontal support.
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
📊#MC is moving in an ascending triangle. Currently, it is rejecting from the horizontal resistance. The Ichimoku cloud is acting as resistance. MACD crossover is showing bullish momentum. 👀
A solid breakout of the ascending triangle would be the bullish confirmation and in case of rejection, it will test the ascending trendline support.✅
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️