Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
According to @/mkgenie, the president of Michael Jackson's Chinese fanclub, and that had access to the list of recording artists of the MJ tribute project in 2023, Jungkook was one of the renowned singers that would get to sing one of the 10 never-released song written by Michael Jackson along with Bruno Mars, Doja Cat and Sza!
#JUNGKOOK
•@OUR_7_PRINCES•
“Yes, Love him! Incredible! His dancing, singing, songs, incredible machine. I love that dude, like he’s incredible”
— Omar Rudberg, a Venezuelan-Swedish singer and actor, about #Jungkook
#JUNGKOOK
•@OUR_7_PRINCES•
Rolling Stone UK Twitter Update
Read the full interview with #JungKook here
https://www.rollingstone.co.uk/music/features/jung-kook-bts-interview-rolling-stone-photos-57298/
-@All_BTS_Updates
GameSpot, a major American website providing news & reviews about video games, wrote an article about #Jungkook
“BTS's Jungkook Is A Streamer Now, Here Are The Games He's Played So Far”
https://www.gamespot.com/gallery/btss-jungkook-is-a-streamer-now-here-are-the-games-hes-played-so-far/2900-7286/
#INFO
•@OUR_7_PRINCES•
Famous actor Manny Jacinto said #Jungkook was his bias in a recent interview for Cosmopolitan
Q: Recently, a photo of you at a j-hope concert made the internet rounds. Who is your BTS bias?
🗣️ “Jungkook. I was a dancer, and I have this theory. Jungkook apparently trained in Los Angeles when he was younger, and I think we almost crossed paths and trained in the same studio around the same time. I mean, he is, like, eight years younger than me, but I saw videos and pictures of him training at the same studio. And I was like, wait, when was this? And this was around the same time, like, summer of 2012, 2011. I think he’s one of the best dancers on the team. But I also just dig his music.”
#INFO
•@OUR_7_PRINCES•