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

Резултати

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

Пребарај: #lunarnewyear2024

当前筛选 #lunarnewyear2024清除筛选
NEA Singapore

@NEASingapore · Post #756 · 06.02.2024 г., 01:01

Embrace the Lunar New Year with fresh air and festive cheer! Visit go.gov.sg/smoking-prohibition for the list of places where smoking is prohibited. #LunarNewYear2024

NEA Singapore

@NEASingapore · Post #758 · 08.02.2024 г., 01:01

No spring cleaning is complete until you clear away all stagnant water. Let’s bring in good health and fortune, not mosquitoes. 🚫🦟 Check out more dengue prevention tips at go.gov.sg/dengue-checklist #BLOCKDengue#LunarNewYear2024

NEA Singapore

@NEASingapore · Post #767 · 19.02.2024 г., 09:31

Litter can become potential mosquito breeding habitats. Let’s #KeepSGClean and mozzie-free by binning our litter properly! If a bin is full, hold on to your litter until you find a bin that you can use! #LunarNewYear2024

NEA Singapore

@NEASingapore · Post #754 · 04.02.2024 г., 01:01

As we approach the Year of the Dragon, let’s breathe new life into our old tech! Recycle your e-waste to recover precious materials that can be used to make new products. More info at go.gov.sg/e-waste #RecycleRight#SustainableSG#TowardsZeroWaste#LunarNewYear2024

NEA Singapore

@NEASingapore · Post #750 · 01.02.2024 г., 01:05

Are the expiration dates on your condiments and other canned & bottled goods looming? Check your pantry and use up your goods before they expire. Let’s have a sustainable celebration this Lunar New Year! #SayYEStoWasteLess#SustainableSG#TowardsZeroWaste#LunarNewYear2024

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