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

Резултати

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

Пребарај: #healthyhabits

当前筛选 #healthyhabits清除筛选

#WellnessWednesday: Stay Active. Stay Healthy! 💪🏾 Staying active doesn’t always require a gym membership, sometimes it’s the little things that make the biggest impact! 🚶🏾‍♀️‍➡️ Take the stairs instead of the elevator walking 🙆🏾‍♀️ Stretch during work breaks 🗣️ Engage in quick walks or light conversations with colleagues 🧍🏾‍♀️Stay on your feet while prepping meals or organizing your space These simple movements can help reduce stress, improve mood, boost focus, and support your overall health. Whether you’re at home or at work, every step counts! #Wellnesswednesday#NCDCNigeria#HealthyHabits

#FactFriday: Good Food, Good You! 🥬🥦Adding more fruits and vegetables to your meals can be a game changer for your health. They are filled with Vitamins, Minerals and fiber that helps boost your immunity, Protect your heart and lower the risk of chronic diseases. Healthy eating starts with fruits and Vegetables✅️ #FactFriday#HealthyLiving#HealthyHabits#NCDCNigeria.

#Healthtiip Monday: Clean hands, Healthy You! 💦Regular handwashing with soap under running water or using an alcohol-based sanitizer is one of the most effective ways to protect against infectious diseases, including Ebola. In times of outbreaks, this simple habit can make a big difference. ✅ Every wash helps to break the chain of transmission and keep you, your loved ones, and your community safe. #HealthTipMonday#HealthyLiving#HealthyHabits#NCDCNigeria