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

Резултати

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

Пребарај: #inspirational

当前筛选 #inspirational清除筛选
₿usiness Tips | Thoughts 💡

@quotesofzday · Post #269 · 07.08.2022 г., 12:01

Remember, Most of your stress comes from the way you respond, not the way life is. Adjust your attitude. Change how you see things. Look for the good in all situations. Take the lesson and find new opportunities to grow. Let all the extra stress, worrying, and overthinking go. #Inspirational

₿usiness Tips | Thoughts 💡

@quotesofzday · Post #268 · 07.08.2022 г., 11:59

Prioritize your mental and spiritual wellness. Do things that make you happy. Take time to nurture yourself. Don’t rush the process. Don’t judge where you’re at or where you think you should be. Just be kind and patient with yourself. Things are unfolding for you. #Inspirational

₿usiness Tips | Thoughts 💡

@quotesofzday · Post #258 · 05.08.2022 г., 16:01

Wrinkles, scars, imperfections, strengths, & weaknesses - all these made you who you are today - a strong, independent, beautiful human being. Embrace it all with gratitude. When you learn to accept & love everything about you, nobody can ever use it against you. #Inspirational

Quiet World 🍁

@QuietWorld · Post #7360 · 08.06.2020 г., 03:15

“𝕋𝕠 𝕤𝕦𝕔𝕔𝕖𝕖𝕕, 𝕪𝕠𝕦 𝕨𝕒𝕟𝕥 𝕥𝕠 𝕓𝕖 𝕒𝕓𝕝𝕖 𝕥𝕠 𝕣𝕖𝕘𝕦𝕝𝕒𝕥𝕖 𝕪𝕠𝕦𝕣 𝕚𝕞𝕡𝕦𝕝𝕤𝕖𝕤 𝕨𝕙𝕚𝕝𝕖 𝕒𝕝𝕤𝕠 𝕙𝕒𝕧𝕚𝕟𝕘 𝕥𝕙𝕖 𝕚𝕞𝕒𝕘𝕚𝕟𝕒𝕥𝕚𝕠𝕟 𝕥𝕠 𝕤𝕖𝕖 𝕨𝕙𝕒𝕥 𝕥𝕙𝕖 𝕗𝕦𝕥𝕦𝕣𝕖 𝕨𝕚𝕝𝕝 𝕓𝕖 𝕝𝕚𝕜𝕖 𝕚𝕗 𝕪𝕠𝕦 𝕥𝕣𝕪 𝕤𝕠𝕞𝕖𝕥𝕙𝕚𝕟𝕘 𝕟𝕖𝕨.” #selfreminder#motivation#inspirational#life#wisdom#success @quietworld🍃