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

Резултати

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

Пребарај: #speed

当前筛选 #speed清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #1189 · 03.01.2026 г., 22:11

🌎 The peregrine falcon holds the speed record for any animal on Earth. During hunting dives called “stoops,” it can reach over 320 kilometers per hour. This speed helps it catch birds in midair. ✨ #animals⚡#records⚡#speed 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #695 · 05.09.2025 г., 20:22

🌎 The cheetah is the fastest land animal, capable of sprinting up to 112 kilometers per hour for short distances. Its slender body and long tail provide balance while chasing prey across African plains. ✨ #animals⚡#speed⚡#records 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #589 · 19.08.2025 г., 16:22

🌎 Some bamboo species can grow up to 91 centimeters in a single day, making bamboo one of the fastest-growing plants on Earth. This rapid growth helps bamboo quickly regenerate after being harvested and provides vital habitats for many animals. ✨ #botany⚡#speed⚡#ecosystems 👉subscribe Interesting Planet

Universe Mysteries 🪐

@cosmomyst · Post #222 · 04.09.2025 г., 20:11

🪐 The pulsar PSR J1748−2446ad in the globular cluster Terzan 5 holds the record as the fastest-spinning known pulsar, rotating an astonishing 716 times per second. Pulsars are ultra-dense neutron stars that emit narrow beams of radiation, and this particular cosmic beacon spins so rapidly that its surface moves at about a quarter of the speed of light. ✨ #pulsars⚡#neutronstars⚡#speed⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Interesting Planet 🌍

@interesting_planet_facts · Post #524 · 08.08.2025 г., 20:22

🌎 Lightning-fast, the peregrine falcon dives at up to 320 km/h, making it the fastest animal on Earth. Specialized nostrils and strong muscles let it hunt mid-air with pinpoint accuracy. ✨ #falcon⚡#speed⚡#wildlife 👉subscribe Interesting Planet

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