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

Пребарај: #september

当前筛选 #september清除筛选
悦读「优质少量RSS聚合」

@Dailyrss · Post #13121 · 28.09.2025 г., 00:45

Wikipedia每日一图(#September 28, 2025)https://ift.tt/Jhp6sa7 French chemist and microbiologist Louis Pasteur photographed by Nadar. Renowned for his scientific discoveries, he saved millions by developing vaccines for rabies and anthrax, as well as the process of pasteurization. He died on this day 130 years ago.. 了解更多 . #Wikipedia每日一图

悦读「优质少量RSS聚合」

@Dailyrss · Post #13120 · 27.09.2025 г., 00:45

Wikipedia每日一图(#September 27, 2025)https://ift.tt/suPWQxz Panoramic view of the west bank of Nigeen Lake in Srinagar, India, with the distant Middle Himalayan Pir Panjal mountain range in the background. The city, situated on the banks of the Jhelum river and several lakes in the Himalayan Kashmir Valley, is the summer capital of Jammu and Kashmir and the northernmost million-plus city of India.. 了解更多 . #Wikipedia每日一图

悦读「优质少量RSS聚合」

@Dailyrss · Post #13119 · 26.09.2025 г., 00:45

Wikipedia每日一图(#September 26, 2025)https://ift.tt/0kyxNdY An image of Arab twin brothers Saints Cosmas and Damian from the Grandes Heures of Anne of Brittany. As ancient physicians, they are depicted holding tools of their profession. Today is their feast day on the General Roman Calendar.. 了解更多 . #Wikipedia每日一图

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