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

Резултати

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

Пребарај: #sentinels

当前筛选 #sentinels清除筛选
NewUU Student Council

@newuu_sc · Post #671 · 23.06.2023 г., 11:35

📢 Election Update: Renaissance Team Emerges Victorious!🎉 We are thrilled to announce the conclusion of the Student Council elections, held online through Google Forms from June 20 to 22. After an intense battle for leadership, the results are finally in! ✨ Team Renaissance has emerged as the winner, securing an impressive 59.3% of the votes! 🎊 We extend our warmest congratulations to their members for their outstanding campaign and commitment to making a positive impact on our school community. 🏅 We also commend the Sentinels team for their dedication and hard work, as they garnered a respectable 40.7% of the votes. Your participation and contributions have been invaluable throughout this process. We would like to express our gratitude to all candidates who put themselves forward for the Student Council elections. Your passion, ideas, and willingness to serve are truly commendable. A special thanks goes out to every student who participated in the voting process. Your engagement and enthusiasm have played a crucial role in shaping the future of our Student Council and the initiatives it will undertake. Let us now join hands and offer our full support to the Renaissance Team as they embark on their journey of leadership. Together, we can strive to create an inclusive and vibrant school environment that fosters growth, innovation, and collaboration. Best Regards, Student Affairs. 🎓🌟#StudentCouncilElections#Renaissance#Sentinels#Congratulations

NewUU Student Council

@newuu_sc · Post #639 · 14.06.2023 г., 09:06

📢 Attention all students of New Uzbekistan University! 🎓 The highly anticipated debates between the two candidates vying for the position of President of the Student Council will take place in the university Conference Hall. 🎙🏛 Join us for an engaging discussion as these candidates present their visions, plans, and goals for the next academic year. It's an excellent opportunity to get to know the potential leaders who will shape our university's future! 🌟✨ Whether you're passionate about academic improvements, extracurricular activities, or enhancing student welfare, this debate is the perfect platform to hear the candidates' perspectives and evaluate their abilities to meet our diverse needs. 📚🎉 Spread the word and see you all there! 🎉🗣 Date: June 16 Time: 16:00 Location: Conference hall #NewUzbekistanUniversity#StudentCouncilElections#Debate2023#Renaissance#Sentinels