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

Пребарај: #secondseason

当前筛选 #secondseason清除筛选
MoonPlay

@moonplay_official · Post #93 · 15.08.2024 г., 07:15

Let’s Conquer the Moon Together!🌕 Just landed on To The Moon!? Don’t worry - you’re joining at the perfect time as we kick off Season 3! Here’s how it works: 💸 mine Space Bucks, 🚀 upgrade your ship, 👥 invite friends & recruit a stellar crew, 🌌 play Star Dust to gain even more SP, 🏆 set off to the moon and level up! Every step you take brings you closer to token airdrop💸 after all 5 seasons. Focus on missions, levelling up, inviting referrals, and growing your space bucks balance. And for those of you who are starting out now, you’ve still got a shot at the airdrop by playing, conquering, and contributing to the mission. Ready to explore? Your adventure awaits! 👉TO THE MOON APP👈 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#ecosystem#blockchain#gamefi#web3#wenlisting#secondseason#communitymilestone#communityfirst#taptap#clicker#game

MoonPlay

@moonplay_official · Post #91 · 14.08.2024 г., 07:46

Shine Bright with Your Season 2 Badges and Win Big! 🪙 Season 2 was definitely one to remember: fierce competition, amazing Space Bucks balances, crazy level-ups 🆙, completed missions, and tons of new players joining To The Moon! via referral links 🤝. We've got plenty of reasons to celebrate! Just like we did in July - share your Achievement Badge from Season 2 2️⃣, and you could win a prize equal to the Space Bucks balance on it! Here's how to join in: 1️⃣ Follow the @moonplay_official group. 2️⃣Join our lively chat at @moonplay_chat. 3️⃣Drop a screenshot of your Season 2 Achievement Badge + use a hashtag #Season2 in the comments below this announcement. ⭐️To find your Season 2 Badge, just tap your profile in the top right and look under the Loot Capsules. We'll pick 20 lucky winners in 24 hours, so keep your eyes peeled! Good luck, and may your Badge shine the brightest! 👉TO THE MOON APP👈 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#ecosystem#blockchain#gamefi#web3#wenlisting#secondseason#communitymilestone#communityfirst#taptap#clicker#game