Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#BIFI/USDT analysis :
#BIFI is currently experiencing a bearish trend, trading below the 200 Exponential Moving Average (EMA). The price is approaching the resistance zone, coinciding with the 200 EMA, and is anticipated to test this level. It is expected to reverse from this point, resuming the bearish momentum and targeting the swing low level.
TF : 2H
Entry : $192
Target : $161
SL : $208
#BIFI/USDT analysis :
#BIFI is in a downtrend, creating new lower lows and lower highs below the 200 EMA. Currently testing a resistance zone, a rejection is anticipated, which will lead to a decline towards the swing low level.
TF : 4h
Entry : $254
Target : $216.7
SL : $274
#BIFI/USDT analysis :
#BIFI has broken and retested the resistance zone, which was formerly a support level. The next expected move is to test the resistance zone and subsequently resume its bearish momentum to revisit previous lows.
TF : 1h
Entry : $281.6
Target : $262.9
SL : $293.3
#BIFI/USDT analysis :
#BIFI has breached previous support zone and is currently trading below it. The price is anticipated to persist in its bearish structure and test prior lows.
TF : 2h
Entry : $307.4
Target : $282.6
SL : $324
Our algorithm detected ascending triangle at #BIFI (4h) chart 👀
Normally, an upside breakout is expected in this triangle type, but indicators give us mixed signals 🤔
Therefore, it would be logical to wait for a directional breakout and then open a position.
Targets are on the chart.
#ZIL LONG
▪Вход ZIL : 0.0225$
▪Тейк: буду обновлять.
#BIFI LONG
▪Вход BIFI : 380$
▪Тейк: буду обновлять.
пс: учитываем, что это альткоины... торгуем соблюдая риски.
LINK - Maximus Trade|TWITTER