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

Резултати

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

Пребарај: #gamelaunch

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

@singsingchannel · Post #1130 · 24.12.2024 г., 01:25

🌟Mystic Garden is Officially Open!🌟 🎉 The wait is over—step into the magic now! 🔸AURA Launchpool Stakers: Your AURA rewards are ready! 🔸Beta Testers: Enjoy 2x AURA on your deposits and beta test reward as a special thank-you! 🔸Everyone: It’s time to explore, grow, and thrive in Mystic Garden! Let the adventure begin! 🌱✨ Play Now: https://t.me/mystic_garden_bot/app #MysticGarden#GameLaunch#AURARewards

SingSing Announcement

@singsingchannel · Post #1125 · 22.12.2024 г., 02:05

🎄Christmas is Coming... and so is Mystic Garden!🌟 This holiday season, unwrap the magic with the official launch of Mystic Garden on Dec 24! 🌱✨ Get ready to plant, harvest, and earn as the garden blooms with festive cheer. 🎁 Don’t miss it! #MysticGarden#GameLaunch#PlayToEarn#Web3Gaming

SingSing Announcement

@singsingchannel · Post #814 · 21.09.2024 г., 05:07

🚀 The long-awaited SingSing Tycoon Game is about to launch! 🚀 ⏰Save the schedule:14:00 UTC Today - Sep 21⏰ In just a few hours, you’ll officially step into the world of SingSing Tycoon! Get ready to build your own karaoke chain, upgrade booths, expand your shop, and grow your ultimate entertainment empire! 🎤💰 Exciting adventures await. Be prepared—this is going to be epic! 💥 #SingSingTycoon#GameLaunch#KaraokeEmpire#PlayToEarn#SingSing Announcement | Chat | X (Twitter) | Website | Game

SingSing Announcement

@singsingchannel · Post #816 · 21.09.2024 г., 16:57

🚀SingSing Tycoon Game is Officially LIVE!🚀 The wait is over, SingSing Tycoon Game is Live Now 👉https://t.me/SingSing_TG_bot/app?startapp=_ktvgame Build your empire, compete with friends, and rise to the top! 💼🏆 Note: Lucky Box Owners and Kara Box Owners can now unbox in the Tycoon Game! 🎁✨ Don’t miss out—start your journey today! 🎮 #SingSingTycoon#GameLaunch#PlayNow#BuildYourEmpire 🎤Announcement | Chat | X (Twitter) | Website | Game