Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#MANA/USDT analysis :
#MANA is currently in a correction phase. It is advisable to wait for the price to test the support zone before considering a long entry. With bullish momentum expected to continue, the price is likely to revisit previous highs.
TF : 1W
Entry : $0.4158
Target : $0.8556
SL : $0.3117
#MANA/USDT analysis :
#MANA is currently forming lower lows (LLs) and lower highs (LHs) while trading near the resistance zone. The price is expected to decline from this level and test previous lows. For a short entry, it is advisable to wait for a break below the $0.3370 level.
TF : 1D
Entry : $0.3370
Target : $0.2713
SL : $0.3752
#MANA is currently trading around $0.2843, testing a critical support zone ($0.25 - $0.28).This level previously acted as a strong demand zone in September 2024 before the major uptrend.🔥✅
Further,MANA is testing a critical support zone ($0.25 - $0.28). If buyers hold this level, we could see a bounce toward $0.35 - $0.38. However, a breakdown below $0.25 could lead to a further drop toward $0.20 - $0.22 .🔥✅😍👀✅🔥
#MANA has tested the SR zones and formed upside liquidity. It is forming a correction/HL till golden ratio and took small correction.🔥✅
Further, MANA have potential to go for 500% profit in ALT season .🔥✅😍👀✅🔥😳
💰#MANA has a rising wedge pattern on 6H Time frame,we expect another bullish leg from the Green zone,send it to the next level 🚀
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️