Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#Musical chair
Activity for review vocabulary
Class 7️⃣"Active"
Students learned vocabulary Time⏰
On each chair stuck the words from the topic time
When music🎶 plays students walking around the chairs and dance 🕺💃
When music pauses they should sit and say the word with its meaning
The challenge is that students' numbers are more than chairs. And also if students can not say the meaning they can not participate in the activity anymore
Aim of the activity
Review vocabulary
Enhance vocabulary ⬆️
Motivate students to learn foreign language
Relaxation 😂
Work on concentration🤔
Energizer😉
Learning should be
Easy and Enjoyable 😎👍
Teacher Umida Pulatova
Kushtepa district Specialized School
Fergana Region
https://t.me/LanguageStuff
🎬 Whiplash: Em Busca da Perfeição (2014)
Gênero: #Drama, #Musical
⭐️ IMDb: 8.5
⏳ Duração: 1 h 46 min
📝 Sinopse:
Um jovem e promissor baterista se matricula em um conservatório de música onde seus sonhos são guiados por um instrutor que não pára por nada para perceber o potencial de um aluno.
Fonte: IMDb
🔵Inscreva-se em @Assistir
*Patrocinado: Anime Bot
📺- CHICA VAMPIRO -📺
Título original: Chica Vampiro
Género:#Fantasía#Musical
Temporadas: 1
Año: 2013 📼
Origen: Colombia 🇨🇴
Tráiler:youtu.be/tlNRg_fYFU4
Sinopsis:
Daisy O'Brian es una chica normal que sueña con una carrera como cantante en comedia musical. Sus padres son vampiros y, según la tradición familiar, debe decidir convertirse en vampiro o no en su cumpleaños número 16. Ese día, Daisy decide seguir siendo humana para vivir junto a su amor, Max, que es su vecino y compañero de clase.
Disponible:Netflix | Vix | HBO Max
@SeriesClubHD
🍿 Lady Gaga and Joaquin Phoenix unleash chaos in 'Joker: Folie à Deux'
📆Premiere: October 4, 2024
🎭Genre: #Drama · #Musical
🎬 The first trailer for 'Joker: Folie à Deux' is here! Joaquin Phoenix returns as Arthur Fleck, joined by Lady Gaga as Harley Quinn. This dynamic duo promises chaos and music in a sequel that takes place mostly in Arkham Asylum. 🌆🃏
The first film was a massive hit, winning the Golden Lion and multiple Oscars, including Best Actor for Phoenix. This time, in addition to the usual madness, we'll see unique musical elements that will surprise everyone. Don't miss it! 🎤💥