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

Резултати

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

Пребарај: #newindia

当前筛选 #newindia清除筛选
MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #13379 · 14.04.2025 г., 06:44

From Runways to Sky-High Stats ✈️ India’s passenger traffic soars 143% — a testament to rising infrastructure, connectivity & progress! #NewIndia

Hashtags

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12790 · 05.06.2023 г., 13:02

Exciting opportunity to test your knowledge and contribute to nation-building 📝🧾 Take part in the '9 Years of Seva, Sushasan aur Garib Kalyan' Mahaquiz 2023 and celebrate the progress made towards #NewIndia. Visit: https://quiz.mygov.in/quiz/9-years-seva-sushasan-aur-garib-kalyan-mahaquiz-2023/

Hashtags

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12691 · 10.05.2023 г., 08:52

Modern stations for a modern India! With state-of-the-art facilities & world-class amenities, the upgraded railway stations will be a reflection of #NewIndia's progress

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12283 · 09.03.2023 г., 07:09

Capture the transformation of #NewIndia with your lens! Participate in contest and get a chance to win exciting cash prizes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12181 · 27.02.2023 г., 11:14

Show #NewIndia with your lens! Participate in "Inviting Videos of Transformative Impact" and highlight the benefits received from particular schemes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12143 · 23.02.2023 г., 15:11

Calling all creative minds to compose a Jingle for the 100th episode of Mann Ki Baat Participate & get a chance to make your jingle remain in the minds and hearts of #NewIndia Visit: https://secure.mygov.in/task/compose-jingle-100th-episode-mann-ki-baat/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12142 · 23.02.2023 г., 14:10

Show #NewIndia with your lens! Participate in "Inviting Videos of Transformative Impact" and highlight the benefits received from particular schemes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12118 · 20.02.2023 г., 09:09

Here's a platform to showcase the #NewIndia Share your Before and After videos and describe how a particular scheme of government has benefited you Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #11479 · 29.11.2022 г., 08:10

Are you the next best-selling author of #NewIndia? We are looking for you! Apply for YUVA 2.0 and get mentorship, stipend and much more! Know more here : innovateindia.mygov.in/yuva/

Hashtags

123•••10•••20•••2526
ПретходнаСтраница 1 од 26Следна