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

Пребарај: #gemswall

当前筛选 #gemswall清除筛选

🪙 TON BuildCon – Defining the Future of TON in 2025! What narratives will shape TON in 2025? What innovations and trends will drive its growth? Let’s find the answers together at TON #BuildCon – an online event by PumpStep & OpenSourceFun, focused on TON Blockchain. 🗓Date: February 12th, 15:00 UTC ➡️Live Twitter Space ➡️Register on Luma What’s on the agenda? ⏺ The $TON Era for #TelegramApps ⏺ Technical Challenges & New Opportunities in TON ⏺ Telegram as an On-Chain Hub for Retail Users 🎙 Featuring industry experts from: #Tonkeeper, #StormTrade, #EVAAProtocol, #GemsWall, and more! ✔️ As an official media partner, we’ll be covering all key insights from the event – stay tuned!

🎁Get your Delea x GemsWallSBT #Gemswall is a quest platform where you can complete tasks, participate in quests, and earn rewards within the Telegram ecosystem. How to get your SBT and share of the $1.5M TON airdrop? ✔️ Go to the Delea quest on GemsWall ✔️ Follow the socials ✔️ Go to Delea App and connect your wallet ✔️ Deposit $20 worth collateral and mint (borrow) 15+ $DONE stablecoin 🏆Pro tip: To boost your rewards, join #TheOpenLeague, where #Delea is competing: Get your SBT badge, earn points for every $20 liquidity position & grab your share of the $1.5M airdrop! 💎Claim your SBT before December 16 — time is runningout! #SBT#stablecoin#LEA#DONE