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

Резултати

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

Пребарај: #shrovetide

当前筛选 #shrovetide清除筛选
Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4284 · 01.03.2025 г., 12:00

🥞Russian Blini: A Quick Recipe Ingredients: ☆1 cup milk ☆1 cup flour ☆1 egg ☆1 tablespoon sugar ☆Pinch of salt ☆2 tablespoons melted butter (plus extra for greasing) Instructions: 1. Whisk together milk, egg, sugar, and salt. 2. Gradually add flour, whisking until smooth. 3. Stir in melted butter. 4. Let batter rest for 15-30 minutes. 5. Lightly grease a hot pan. 6. Pour 1/4 cup batter onto the pan for each blini. 7. Cook for 1-2 minutes per side, until golden brown. 8. Serve warm with your favourite toppings (sour cream, jam, red caviar). 💢 By the way: • Печь блины [pech bli-ny] doesn't only mean to bake blini but also to skip pebbles on the water. Did you know it? Video: AI Pinterest 😋Yummy! What's your favourite topping/filling for Russian blini? #Russian_cuisine #holidays #Shrovetide 😎 Stay with @learnRCRussian

Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4287 · 02.03.2025 г., 07:19

🌝С Масленицей! Happy Shrovetide! 🔻Maslenitsa (or Shrovetide), a week-long traditional Russian festival before Lent, culminates in Forgiveness Sunday. 🔻This significant day precedes Great Lent, marking a time for asking forgiveness and reconciliation. 🔻The week-long celebration leading up to it features the vibrant Russian tradition of Maslenitsa, including feasts, games like the thrilling greased pole climb, the burning of a winter scarecrow, and joyous performances of folk songs, lively chastushki (short humorous Russian songs), and energetic Russian folk dances. 🔻Maslenitsa remains incredibly popular, showcasing Russia's rich cultural heritage and is celebrated by Russians not only in Russia but in other countries as well. Video: an episode from Russian film Сибирский цирюльник by Nikita Mikhalkov (1998) #Maslenitsa #Shrovetide #holidays #Russian_culture #ForgivenessSunday 😎 Stay with @LearnRCRussian