Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
¿Que puede hacer este bot?
@ClearURLs_Bot
Convierta cualquier URL de seguimiento en una URL clara que no contendrá ningún ID de seguimiento desagradable
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces
¿Que puede hacer este bot?
@DirectFileLinkBot
Este bot genera un enlace de descarga directa de archivos de Telegram.
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@FileSharerRobot
Este bot puede ayudarlo a crear un enlace para compartir archivos de Telegram
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@Qualyuploadbot
Envíe cualquier enlace URL de descarga directa, y el bot subirá a telegram como archivo / video
Idiomas: inglés
(visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@XFiles2LinkBot
Este bot ofrece enlaces de descarga para archivos de telegram
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descargas
¿Que puede hacer este bot?
@MultiURLShortenerBot
Este bot puede darle 14 enlaces cortos desde diferentes plataformas.
Simplemente envíe el enlace y elija la plataforma preferida
Idioma: inglés
(Visto en @botsgram_cu)
#enlaces#acortador
¿Que puede hacer este bot?
@url_io_bot
Este bot sirve para acortar y personalizar enlaces.
Idiomas: inglés, portugués y español
(Visto en @botsgram_cu)
#acortador#enlaces
¿Que puede hacer este bot?
@QrCodeMakerRobot
Este Bot puede convertir su enlace en una imagen QrCode personal.
Idiomas: inglés
(Visto en @botsgram_cu)
#qr#enlaces
¿Que puede hacer este bot?
@leoanydlbot
Con este bot puedes descargar videos de varias fuentes
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga#videos
¿Que puede hacer este bot?
@TGYouTube_Bot
Este bot puede convertir el enlace de Youtube a video / archivo y MP3 con soporte de miniaturas personalizadas
Idiomas: inglés
(Visto en @botsgram_cu)
#descarga#enlaces#youtube