Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
Here are some ways to keep your food safe from rodents⬇️
✅Store your food in tightly covered containers
✅Clean your environments regularly
✅Put rodent repellents around your food store
✅Seal all cracks, gaps, or holes in your homes to prevent entry of rodents
#STOPLassaFever
Rats and mice constantly urinate & defaecate, contaminating every surface they touch
Keep your homes & communities clean to prevent direct or indirect contact with rats
➡️Properly dispose of waste from your homes
➡️Do not defecate in open areas
➡️Sweep your floors regularly, removing crumbs or food remnants
#STOPLassaFever
Not all fevers are malaria!
Report early to a healthcare facility when experiencing #LassaFever-associated symptoms.
Early symptoms of #LassaFever include fever, body weakness, sore throat, muscle & chest pain, nausea, vomiting, diarrhoea, cough & abdominal pain.
#STOPLassaFever
Do NOT eat food or drink water contaminated with the urine, faeces, saliva, or blood of rats.
Food safety is key in the prevention of #LassaFever:
✅Store all foods properly in tightly closed containers
✅Ensure proper hygiene when preparing & eating food
#STOPLassaFever
Food safety is key in the prevention of infectious diseases like #LassaFever.
Maintain these safety measures :
✅Store all foods properly in tightly closed containers
✅Ensure proper hygiene in the preparation & consumption of food
#STOPLassaFever
Preventing #LassaFever starts with simple habits!
Remember: 20 seconds of regular handwashing with soap and water can save lives🧼
Let's keep our hands clean and our loved ones safe.
#STOPLassaFever#HandHygiene
🛑 Lassa Fever is highly infectious!
Your hands can carry more than you think — keep them clean to stay safe.
🧼 Wash regularly with soap under running water.
💪 Protect yourself. Protect others.
#LassaFever#HygieneIsKey#NCDCNigeria#StopLassaFever