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

Резултати

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

Пребарај: #traderoutes

当前筛选 #traderoutes清除筛选
Crypto M - Crypto News

@CryptoM · Post #64616 · 09.04.2026 г., 11:04

🚀 Hormuz Shipping Crisis Presents Opportunity for Canada to Mend Ties with Trump The ongoing shipping crisis in the Strait of Hormuz has opened a diplomatic window for Canada to improve relations with U.S. President Donald Trump. Bloomberg posted on X that the situation has escalated tensions in the region, affecting global oil supply routes. Canada, with its strategic position and resources, is in a unique position to offer assistance and mediate in the crisis. The Strait of Hormuz is a critical chokepoint for the global oil trade, and recent disruptions have raised concerns over energy security. As a major oil producer, Canada could play a pivotal role in stabilizing the situation by increasing its oil exports to offset potential shortages. Furthermore, this crisis presents an opportunity for Canada to strengthen its diplomatic ties with the United States. By offering support and collaboration, Canada can demonstrate its commitment to regional stability and international cooperation. The Canadian government is reportedly considering various options to address the situation, including diplomatic engagement and increased energy exports. This approach could not only help alleviate the immediate crisis but also pave the way for improved bilateral relations with the U.S. under President Trump's administration. As the situation develops, Canada’s actions could have significant implications for both regional stability and its relationship with the United States. #HormuzCrisis#Shipping#CanadaUSRelations#Diplomacy#OilTrade#EnergySecurity#InternationalRelations#GlobalOilSupply#Geopolitics#TradeRoutes