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

Резултати

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

Пребарај: #anc113

当前筛选 #anc113清除筛选
Russian Consulate in Cape Town

@rusconct · Post #2143 · 12.01.2025 г., 14:08

🇷🇺🇿🇦Ambassador of Russia to South Africa Roman Ambarov attended the celebration of the 113th anniversary of the formation of the African National Congress in Cape Town. «To quote Oliver Tambo, the formation of the ANC was a continuation in Southern Africa, under new historic conditions, of the anti-colonial and national liberation struggles which had begun with the advent of colonialism. The Soviet Union, throughout its entire history, consistently stood for the elimination of colonialism and supported liberation movements in Africa and across the globe,” the Ambassador said on the sidelines of the event. “However, the work on decolonization spearheaded by the USSR in the XX century was not finished. And today Russia and South Africa are among the most vigorous supporters of anti-neocolonial policies,” Roman Ambarov pointed out. 🤝The ANC participates in the work of the international forum “For the Freedom of Nations!” seeking to wipe out modern practices of neocolonialism. In Dec 2024, Pretoria voted for the UNGA resolution on the eradication of colonialism in all its forms and manifestations. “We hope our collaboration will help mobilize all responsible members of the international community to uphold justice in world affairs,” the Ambassador added. #RussiaSouthAfrica#RussiaSArelations#StopColonialism#StopColonialismNow#Ambarov#ANC113Anniversary#ANC113@MYANC