Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
😄Consider
➖➖➖➖➖➖
🔘 The verb, consider can mean spend time to think, or think about something
🔜 I'm going to take some time to consider, then I'll tell you my decision.
🔜I'm considering how we can best use our time.
🔘 Consider can have a similar meaning to 'take into account' to say that somethng is important when making a decision or judgement.
🔜 She's learnt so much, considering how late she started the course.
🔘 Consider can be used with an object and an adjective or noun to describe what we think something or someone is like.
🔜 I consider him to be the best writer of his generation.
🔜 I consider her an expert. She knows so much about history.
#Consider👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Consider
➖➖➖➖➖➖
🔘 The verb, consider can mean spend time to think, or think about something
🔜 I'm going to take some time to consider, then I'll tell you my decision.
🔜I'm considering how we can best use our time.
🔘 Consider can have a similar meaning to 'take into account' to say that somethng is important when making a decision or judgement.
🔜 She's learnt so much, considering how late she started the course.
🔘 Consider can be used with an object and an adjective or noun to describe what we think something or someone is like.
🔜 I consider him to be the best writer of his generation.
🔜 I consider her an expert. She knows so much about history.
#Consider👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Consider
➖➖➖➖➖➖
🔘 The verb, consider can mean spend time to think, or think about something
🔜 I'm going to take some time to consider, then I'll tell you my decision.
🔜I'm considering how we can best use our time.
🔘 Consider can have a similar meaning to 'take into account' to say that somethng is important when making a decision or judgement.
🔜 She's learnt so much, considering how late she started the course.
🔘 Consider can be used with an object and an adjective or noun to describe what we think something or someone is like.
🔜 I consider him to be the best writer of his generation.
🔜 I consider her an expert. She knows so much about history.
#Consider👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
📰Colorado Lawmakers Consider Bill Allowing Older Adults to Opt Out of Jury Duty in State Courts
🔗https://dailycoloradonews.com/colorado-lawmakers-consider-bill-older-adults-opt-out-jury-duty/?utm_source=telegram&utm_medium=social&utm_campaign=zimm-distribute
via Daily Political Press
#Courts#Colorado#Lawmakers#Consider#Latest
📰Colorado Lawmakers Consider Bill Allowing Older Adults to Opt Out of Jury Duty in State Courts
🔗https://dailycoloradonews.com/colorado-lawmakers-consider-bill-older-adults-opt-out-jury-duty/?utm_source=telegram&utm_medium=social&utm_campaign=zimm-distribute
via Daily Political Press
#Courts#Colorado#Lawmakers#Consider#Latest