Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#CHESS/USDT analysis :
#CHESS is currently in an uptrend, consistently making higher highs (HHs) and higher lows (HLs), while finding support along the trendline. A breakout above the counter-trendline is anticipated, which will lead to a test of previous highs.
TF : 1D
Entry : $0.1945
Target : $0.2730
SL : $0.1586
#CHESS/USDT analysis :
#CHESS is currently going through a correction phase and retracing back to the 200 EMA before continuing its bearish move. The price is bouncing back from the support line and is expected to test the 200 EMA.
TF : 1h
Entry : $0.1358
Target : $0.1419
SL : $0.1315
#CHESS (Binance Futures and Spot)
✅Sub $10 million market cap coin
✅Fully bottomed
✅Loking exactly like MYX at $1, before making a 1800% move to $18
CHESS is an easy 10x move, grabbing a big bag here below $0.05
#CHESS (Binance Futures and Spot)
✅Sub $10 million market cap coin
✅Fully bottomed
✅Loking exactly like MYX at $1, before making a 1800% move to $18
CHESS is an easy 10x move, grabbing a big bag here below $0.05
LONGING $CHESS HERE
Exchanges: Binance (Spot and Futures)
#CHESS is not only a gem, it’s what we call a once in a lifetime trade. Fully bottomed, momentum stronger than anything we’ve seen, and an easy short term target at $0.25 - $0.5. Buy it below $0.045 while you can
Entry: Below 0.045
Targets: 0.047 - 0.049 - 0.052 - 0.059 - 0.072 - 0.095 - 0.120 - 0.142 - 0.231 - OPEN
SL: Below 0.034