Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#GMT/USDT analysis :
Following the breakout and subsequent retest of the 200 EMA, the price is now declining. It is anticipated that this downward momentum will persist, leading to a test of lower levels.
TF : 4H
Entry : $0.1586
Target : $0.1414
SL : $0.1670
#GMT/USDT analysis :
#GMT is in an uptrend on LTF. The price has broken and retested the 200 EMA. Currently, the price is bouncing back from the 200 EMA and is expected to continue its bullish momentum.
TF : 30min
Entry : $0.1132
Target : $0.1199
SL : $0.1089
#GMT overall trend is bearish, with a significant downtrend visible from the peak in late December.Price has been making lower highs and lower lows, indicating continuous selling pressure. 🔥👍✅
Further,As long as the price stays below $0.0847, the bearish trend remains strong.A potential relief bounce could occur, but confirmation is needed.Bulls need to reclaim resistance levels above $0.0847 to signal a possible trend reversal.👍🔥✅
#GMT is testing the major support zone and testing the Daily range low. Market is taking a correction before going up and we can see big moves in coming months.🔥✅
Further. GMT is looking good for investment in upcoming Alt Season.🔥✅😍👀✅🔥😳
#GMT will test the resistance zone and it has caused the liquidity on resistance zones .Market can see a breakout and bullish move soon,🔥✅
Further, market will take a bullish soon ahead as BTC.D will soon take a breakdown.🔥✅😍👀✅🔥😳
🔵#GMT price is rising in a Bullish channel on 6H Time frame,we expect it will have another bullish leg from the bottom of this pattern 👀
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️