Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
$PEPE 🐸 has had quite the leap, falling 50% from its high, but the charts suggest a frog-leg kickback might be in sight! Can it reclaim $0.0000014 by Feb end? Only time will tell. #PEPE#Crypto#PricePrediction#Trading📈
📈BTC price at the time of this post: $48041
👉Continue reading
Bitcoin Price Prediction for 2025
James Butterfill, CoinShares head of research, forecasts Bitcoin to hit $80K-$150K in 2025. Trump's pre-election promises could influence the price towards the lower end, while better U.S. regulations might propel it higher. Long-term, Bitcoin's market cap may rise to 25% of gold's, potentially pushing prices to $250K, though this is not expected this year. Details: CoinShares Research
#Bitcoin#Crypto#VC#PricePrediction#MarketCap#Regulations#Gold
Bitcoin Price Predictions for 2025
CoinShares' James Butterfill forecasts Bitcoin to reach between $80K and $150K by 2025. Market corrections may arise due to unmet pro-crypto policies under Trump. A favorable regulatory environment could drive Bitcoin's value toward $250K long-term, increasing its share of the gold market from 10% to 25%. Meanwhile, Bhutan's government has mined Bitcoin for over five years, currently holding over $1.1 billion in Bitcoin as of December 2024. Read more
#Bitcoin#Crypto#Investment#MarketTrends#PricePrediction#Regulation#Bhutan#FinTech#Blockchain#VC
🚀 Zcash's Potential Surge: Traders Predict 60% Chance of Reaching $420
Zcash (ZEC) has experienced a significant rise, with traders on Myriad now predicting a 60% probability of the token reaching $420 this month. According to NS3.AI, Zcash saw an increase of over 62% in the past week, with its price recently hovering around $380. The odds on Myriad shifted dramatically from 80% against the move on Thursday to 60% in favor by Friday.
#Zcash#ZEC#Cryptocurrency#CryptoTrading#PricePrediction#Myriad#NS3AI#CryptoSurge#Blockchain#DigitalAssets
Ethereum ETF Sees Major Inflows
The Ethereum spot ETF recorded a net inflow of $139M last week, with Blackrock's Ethereum ETF, ETHA, gaining $135M. However, on January 27, the crypto market saw declines across sectors, with DeFAI down 28.73%. Other sectors like AI Agents saw a 16.91% drop. U.S. crypto czar David Sacks noted ongoing evaluations regarding Bitcoin and digital assets. Meanwhile, Rosseti, Russia's state power company, plans to introduce Bitcoin mining to leverage idle power resources. Runetoshi's new memecoin, Runes, faced volatility, dropping from $28M to $500k in market value. Arthur Hayes predicts Bitcoin could dip to $70,000 before a future rise to $250,000 this year. More on ETF inflows | Market drop details | David Sacks comments | Rosseti's Bitcoin mining | Runes token collapse | Hayes Bitcoin predictions
#Ethereum#ETF#Crypto#Bitcoin#Russia#Mining#Securities#Stablecoins#PricePrediction#DigitalAssets#Memecoin#MarketDrop#Runetoshi#DeFi#AI#QuantitativeEasing#USDC#WhaleAlert#MarketVolatility#FinancialCrisis#ArthurHayes