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

Резултати

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

Пребарај: #countdown

当前筛选 #countdown清除筛选
SingSing Announcement

@singsingchannel · Post #962 · 04.11.2024 г., 14:20

🚀 Only one week left until our IDO launches! The excitement is building up as we get closer to the big day. Get ready to join us on this incredible journey! #IDO#Countdown#SingSing🎉 🎤Announcement | Chat | X (Twitter) | Website | Game

SingSing Announcement

@singsingchannel · Post #952 · 01.11.2024 г., 14:08

🚀 Let’s Countdown Together! 🚀 The big day is coming—SingSing’s IDO is set for November 11! 🎉 Get ready for an epic sale event and your chance to grab $SING! 🔥 Countdown with us on Website and SingSing Mini App! Mark your calendars, bring your best game, and let’s make this an unforgettable IDO together! ⏰ #SingSing#IDO#Countdown#GetReady 🎤Announcement | Chat | X (Twitter) | Website | Game

Oʻzbekiston Qilichbozlik Federatsiyasi

@fencinguzbekistan · Post #3966 · 22.05.2025 г., 05:49

⏳ Countdown is on! Only 26 days left until one of Asia’s biggest fencing showdowns! 🌏🤺 📍 Bali – Indonesia 📆 June 17–23, 2025 🏆 Senior Asian Fencing Championship Top athletes are getting ready for an electrifying competition! Stay tuned for full access 📸 and live highlights from the heart of the action 🎥🔥 #Fencing⚔️#Bali2025#AsianChampionship #FCA#FIE#SeniorAsianFencingChampionship2025 #Indonesia#FencingAsia#Countdown

VISION11

@vision11official · Post #1328 · 02.09.2023 г., 06:02

#Power-packed #battle on the pitch.🔥🔥 Are you ready for an India🇮🇳 vs. Pakistan showdown?💪😎 Make you #teams for #AsiaCup contest and win bumper #rewards.⏳️🏌‍♀️ Only on #Vision11, #download now. #india#cricket#asia#asiacup2023#battle#countdown#begin#cricketfans#reward#bonus#vision#vision11