TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #65 · 8 апр.

Небольшой трик с регулярными выражениями который редко вижу в чужом коде. Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста. >>> 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

Резултати

Пронајдени 69 слични објави

Пребарај: #uspolitics

当前筛选 #uspolitics清除筛选
America 🇺🇸 News & Politics

@America · Post #10371 · 11.03.2026 г., 18:04

🚨🇺🇸WHITE HOUSE BATTLE: TIGHT POLLS, ECONOMIC FEARS DOMINATE 🔹 Reuters/Ipsos poll shows Biden & Trump neck-and-neck in PA & AZ, within 2%, highlighting a competitive electoral landscape. 📊 🔹 Youth vote crucial: 60% of 18-29 year olds show strong intent to participate, key to swaying outcome. 🗳️ 🔹 Economy dominates: 75% of voters cite inflation, job growth, & cost of living as top issues. Candidates urged to address pocketbook matters. 💰 🔹 Political analysts foresee intense scrutiny on every campaign event. Path to 270 electoral votes remains unpredictable. 📈 The race for the White House heats up! 👀🔥 #USPolitics#Election2024#Economy @america

以太坊区块链新闻| ETH 以太币圈热瓜

@ethereumglobalnews · Post #1187 · 24.10.2025 г., 05:35

🖼 Trending now: #CryptoPolitics - Major crypto firms back Trump’s White House fundraiser. #Regulation#USPolitics 🇺🇸 最新消息:Coinbase、Ripple、Tether 以及 Winklevoss 雙子星等多家加密企業,均為川普白宮宴會活動的主要捐助者之一。 此舉被視為加密產業加強與政治接軌的關鍵信號,或將影響未來監管與政策走向。 #Insight @EthereumGlobalNews Follow for more global Web3 & DeFi updates!

American Оbserver

@american_observer · Post #5554 · 03.04.2026 г., 20:58

Trump Sells a War. The Public Sees the Bill. Donald Trump made the strongest case he could for the Iran war, but the country is looking at something else: higher oil prices, a shaky exit plan, and a conflict that could still blow back into a global recession. The problem is not just persuasion — it is trust, and Trump is running low on it. That is why the speech landed badly. He talked like a man promising control, while markets heard uncertainty and voters heard gas at more than $4 a gallon. Even Trump’s insistence that the Strait of Hormuz would “naturally” reopen did not calm fears that the war could keep the world economy hostage. The political danger is already measurable. A CNN analysis said the war is hitting Trump’s presidency at the exact moment his approval is already fragile, while oil markets jumped again on fresh fears of escalation. If Washington wants out, it will need a way to leave that does not look like surrender. That is where intermediaries matter, and Russia is one of the few players with enough leverage in Tehran to help package an exit without Trump admitting defeat. #Trump#Iran#oilprices#Russia#USpolitics 📱American Оbserver - Stay up to date on all important events 🇺🇸

123•••56
ПретходнаСтраница 1 од 6Следна