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

Резултати

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

Пребарај: #aip

当前筛选 #aip清除筛选
Addis Standard

@addisstandardeng · Post #21251 · 30.01.2026 г., 11:59

News: #Ethiopia says official creditors decline Eurobond restructuring terms, plans to reengage Ad Hoc Committee The Ministry of Finance said Ethiopia will not proceed with the implementation of recently agreed #Eurobond restructuring terms after the country’s Official Creditor Committee (#OCC) concluded that the deal does not fully comply with the principle of Comparability of Treatment. In a statement issued on 30 January, the ministry said the assessment followed consultations with the OCC and the International Monetary Fund (#IMF) after Ethiopia reached an agreement in principle (#AIP) on 2 January 2026 with a group of bondholders on restructuring its US$1 billion 6.625% Notes due 2024. According to the ministry, Ethiopia and its advisers engaged the OCC and the IMF to determine whether the AIP was consistent with “(i) the Comparability of Treatment principle as applied by the OCC and (ii) the targets and parameters of Ethiopia’s IMF program.”...... Read more: https://addisstandard.com/?p=54853

100K20

@science_100k20 · Post #109 · 16.10.2023 г., 13:26

Предлагаем ознакомиться с графиком вебинаров от ведущих международных издательств на ближайшую неделю: 📅17 октября 2023 в 17:00 (мск) ✅AIP | Вероятностные модели и их применение Регистрация доступна по ссылке. 📅 18 октября 2023 в 17:00 (мск) ✅Questel | Базовый тренинг по Orbit Intelligence Регистрация доступна по ссылке. 📅18 октября 2023 в 19:00 (мск) ✅ACS | Сила химии: Передовые исследования в области антибиотиков и генной терапии Регистрация доступна по ссылке. #вебинар#исследования#электронныересурсы#наука#библиотека#публикации#ACS#AIP#Questel