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 слични објави

Пребарај: #rgo

当前筛选 #rgo清除筛选

Национальная премия «Хрустальный компас» — одна из самых престижных наград в области географии, экологии и смежных наук! 🏆 В 2026 году уникальные хрустальные статуэтки будут вручены уже в 14-й раз. Лауреатами станут авторы выдающихся исследований и проектов, а также организации и инициативные группы, внесшие значимый вклад в сохранение природы, культурного и исторического наследия. 👩‍🎓 К участию приглашаются: — научные и образовательные учреждения — творческие союзы и организации — общественные деятели и инициативные группы — компании и частные лица из России и других стран. 📋 Приём заявок открыт до 10 февраля 2026 года. Не упустите шанс стать частью международного сообщества, объединяющего исследователей, путешественников и защитников природы более чем из 50 стран мира! 🔗 Подробная информация и подача заявок: https://clck.ru/3PEnsz #ХрустальныйКомпас#RGO#Наука#Экология#Geography#CrystalCompass#Наследие#Премия

خانه روسی در تهران

@Rossotrudnichestvo_in_Iran · Post #802 · 05.09.2024 г., 10:42

🇷🇺🌊🌊🌊 🇮🇳 On September 2, Ratish Nair, Honorary Consul of Russia in Trivandrum (Karnataka, India), began a journey along the route of Afanasy Nikitin. The ambitious project is dedicated to the 555th anniversary of the famous "Journey Beyond Three Seas". 📍 The starting point of the journey was the embankment named after the famous Russian traveler Afansy Nikitin in Tver. ⚡️ Ratish Nair met Senator of the Federation Council of Russia from the Tver Region Lyudmila Skakovskaya and Rector of Tver State University Sergei Smirnov. I am sure that this is a wonderful undertaking - repeating the route of the Tver merchant Afanasy Nikitin. This will help educational and outreach work, draw attention to the traveler's personality, and strengthen ties between our countries. I am sure that in our country, preserving and studying history is one of the most important areas of work, the Senator emphasized. Even in India, not everyone knows that Afanasy Nikitin is the first foreigner who came to our country for peaceful purposes. Friendly relations between India and Russia should be strengthened. This is the main goal of my trip. I am sure that the trip, repeating the path of the Russian traveler, will help to show Russia as it is and open it to foreigners without speculation and fakes, said Ratish Nair. 🗣The meeting participants discussed the opening of Russian online educational courses in Russian in the Indian state of Karnataka, as well as other educational initiatives. 🗺 The head of the Russian House in Trivandrum will visit four more countries after Russia. His route, like 555 years ago, will lie from Tver to Astrakhan along the Volga river, then by car to Derbent, from there to 🇦🇿Azerbaijan, then to 🇮🇷 Iran, from there by plane to 🇴🇲 Oman, and then to 🇮🇳 India. This project is organized by #Rossotrudnichestvo, the Russian Ministry of Foreign Affairs (#MFA), the #RusskiyMirFoundation, and the Russian Geographical Society (#RGS, #RGO), with #Rosatom and #Sber as partners. #RussianHouse#RussianHouseTrivandrum#JourneyBeyondThreeSeas #Voyage555