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

Резултати

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

Пребарај: #udemy

当前筛选 #udemy清除筛选
📗Cursos con Link Directo📕

@cursosmegadrive6 · Post #1180 · 09.12.2023 г., 01:40

🤵🏻Introducción a las Finanzas✨ #Udemy DESCRIPCIÒN: 🔱Finanzas personales con énfasis en inversiones. El curso esta dividido en 32 lecciones didácticas con ejemplos de la vida real sobre las Finanzas que nos rodean, al final del curso tendrás las herramientas necesarias para hacer un análisis general de las finanzas que te rodean.🔱

Hashtags

Libreware

@libreware · Post #1089 · 24.05.2022 г., 23:03

Udeler #Udemy Course Downloader (GUI) A cross platform (Windows, Mac, Linux) desktop application for downloading Udemy Courses. https://github.com/FaisalUmair/udemy-downloader-gui 📡@Libreware

Hashtags

Cursos gratis por mega

@cursosgratismega · Post #710 · 09.04.2022 г., 12:55

Robótica con Matlab y Arduino Modelo y Simulación | #Udemy Robotics, Arduino, Encoders, Control PID, Cinemática, Simulación 3D, Robots móviles, aéreos y manipuladores

Hashtags

Cursos gratis por mega

@cursosgratismega · Post #695 · 31.03.2022 г., 15:38

Crea un Blog y Vive de tu Blog | #Udemy Crea un blog para poder desarrollar tu propio negocio con un método a través de la experiencia de los que ya lo hacen.

Hashtags

Cursos gratis por mega

@cursosgratismega · Post #693 · 30.03.2022 г., 14:26

Cómo ser un Freelancer Exitoso para Diseño y Desarrollo Web | #Udemy Aprende todo para ser Freelancer: Obtener Clientes, Definir Precios y Nicho, Cómo Ganar más y Administrar Proyectos Web

Hashtags

Cursos gratis por mega

@cursosgratismega · Post #691 · 28.03.2022 г., 15:24

Curso de Alemán A1 - Alemán básico para principiantes | #Udemy Aprende lo básico de alemán con música y ejercicios para poder certificarte con el nivel A1 de alemán

Hashtags

Photoshop Tutorial

@Photoshop · Post #361 · 08.07.2020 г., 07:30

🔰 Credit : #Udemy is an online learning and teaching marketplace with over 100000 courses and 24 million students. Learn programming, marketing, data science and more. 🔻 Join us 🔻 ➕@Photoshop ➣ Order here @ads_operator

Hashtags

ПретходнаСтраница 1 од 3Следна