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

Резултати

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

Пребарај: #fish

当前筛选 #fish清除筛选

Hey Skill Labs community, have you already played our fishing game on Discord?🐠🧩 👉 Join our Discord NOW: https://discord.com/invite/skilllabs 👉 Go to the channel called: #fish (in the offtop section) and see the rules in a pinned message 👉 We are currently hosting tournaments!

Hashtags

TonOrbital

@tonorbital · Post #243 · 25.06.2024 г., 18:01

🎉 Exciting News from #FISH! 🎉 Minting for @RetardinoTON gamepass NFTs is now live! 💫 In the upcoming patch, players can also purchase amazing cosmetic items associated with RetarDino partners. 📈 As a bonus, 50% of the profit will go towards the buyback and burn of #FISH tokens. 🎮 Don't miss out—owning an NFT is your exclusive gateway to play and earn $WFOSS. Let the adventure begin!

Hashtags

Beneficial Fishing - You Got 10 BUSD 🤑 Do you remember that Skill Labs launched a Fishing game on Discord? 🔝 We summarized the first results and decided to give 10 BUSD for TOP-5 on the list 🪝 From now, Skill Labs announcing a small tournament for everyone, you play - you earn 👉 Join our Discord and play: https://discord.gg/skilllabs 👉 Go to the channel named: #fish (the offtop section) The results will be published on May 13th 🚀 🐡🐠🐟

Hashtags

Play in Discord and get rewards 🕹 Hey Skill Guilders, let's play the fishing game using our Discord bot 🦈 👉 Join our Discord: https://discord.gg/skillguilds 👉 Go to the channel called: #fish (the offtop section) 👉 There you will see a pinned message with rules and a tutorial on how to play 🧩 Play the game and complete daily quests using the command: %quests Very soon we will launch a tournament among our community, be ready and train yourself 💪 Join now: https://discord.gg/skillguilds

Hashtags

ПретходнаСтраница 1 од 5Следна