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

Резултати

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

Пребарај: #savegaza

当前筛选 #savegaza清除筛选
BadVolf

@badvolfnews · Post #1147 · 20.10.2023 г., 06:25

🚨 Urgent Update: Gaza Humanitarian Crisis 🚨 WHO warns of a "death sentence" for vulnerable hospital patients in Gaza due to Israel's evacuation order. Moving them within 24 hours is impossible and inhumane. UN calls it "impossible" and EU diplomat calls it "utterly unrealistic". Hospitals are at breaking point, with limited electricity and critical shortages. Time is running out to prevent a catastrophe. Urgent delivery of supplies and a humanitarian corridor needed. #SaveGaza#HumanitarianCrisis https://www.aljazeera.com/news/2023/10/13/israels-evacuation-order-for-gaza-death-sentence-for-patients-who-says Subscribe to @BadVolfNews

BadVolf

@badvolfnews · Post #1261 · 12.11.2023 г., 12:25

🚨GENOCIDE ALERT🚨 Gaza is being subjected to a horrifying campaign of violence. Over 11,000 dead, including 1,400 children. Hospitals and schools targeted. Palestinians denied access to basic necessities. This is genocide. We must recognize the humanity of the Palestinian people and demand an end to this atrocity. #SaveGaza#EndGenocide https://www.aljazeera.com/opinions/2023/11/12/genocide-in-gaza-a-call-for-urgent-global-action Subscribe to @BadVolfNews

BadVolf

@badvolfnews · Post #1199 · 01.11.2023 г., 14:25

🔻 Gaza Strip: A graveyard for children. UN warns of more deaths due to dehydration amid Israel's relentless attacks. Over 8,500 Palestinians, mostly children and women, killed. Shocking figures reveal 420 children killed or injured daily. Ceasefire and humanitarian aid urgently needed. Water crisis and trauma pose additional threats. Mental health support desperately required for over 800,000 children. Collateral damage? No safe place in Gaza. International attention needed! #SaveGaza#ChildrenUnderAttack https://www.aljazeera.com/news/2023/10/31/gaza-has-become-a-graveyard-for-thousands-of-children-un Subscribe to @BadVolfNews