Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
#CANNABIS
Il Parlamento israeliano ha approvato nella lettura preliminare una proposta di legge (presentata da Sharren Haskel, di New Hope) volta a riformare l’industria della cannabis medica, estendendo le possibilità di un suo utilizzo. Nello specifico, in assenza della maggioranza sufficiente per poter approvare una normativa finalizzata alla de-penalizzazione del suo utilizzo a scopo ricreativo, si ambisce a realizzare alcune innovazioni in materia: chi otterrà la licenza da parte del Ministero della Salute sarà legalmente autorizzato a coltivare, distribuire e possedere la cannabis a scopi medici.
Adesso, la proposta sarà sottoposta ad una Commissione parlamentare, che la preparerà per la prima lettura nello Knesset.
👉@giurisprudentia
🌿🇺🇸TRUMP FAST-TRACKS MEDICAL MARIJUANA RESCHEDULING
🔹 Executive order directs Attorney General to expedite rescheduling from dangerous Schedule I to Schedule III classification 📋⚡
🔹 Over $30,000 in criminal penalties reduced to civil fines for possession under 1 ounce 💰
🔹 $43,000 average savings per patient annually on medical cannabis costs with insurance coverage 💊💸
🔹 38 states already have medical programs — federal reform finally catching up to reality 🗺️
This policy shift could reshape American healthcare and criminal justice forever 🔥
#USNews#cannabis
✨ More breaking stories coming soon 🚀
@america
#Germania
❗️ Via libera del governo federale tedesco al documento con le linee guida sulla legalizzazione della #cannabis. Il piano, che deve ancora essere trasformato in proposta di legge e votato dal Parlamento, punta a regolare il consumo e la produzione di cannabis, depenalizzando anche l’uso personale ricreativo entro i 30 grammi
@UltimoraPolitics
Standard Wellness Secures $10M Funding
Standard Wellness has successfully raised $10 million in funding as of December 17, 2024. The company is dedicated to enhancing quality of life by providing safe and easy access to cannabis.
#Funding#Cannabis#Healthcare#QualityOfLife#Investment#StandardWellness#Capital#Access#Wellness#Health
Latest Funding Rounds News
Recent funding highlights include:
- Universal Matter: $20M raised on Dec 16, 2024. Visit
- InterCure: $18.20M on Dec 20, 2024. A leading cannabis company. Visit
- Atmo: $17.58M on Dec 20, 2024, developing AI-based meteorology systems. Visit
- Sitemate: $17.20M on Dec 23, 2024, simplifying industrial workflows. Visit
- Meddipay: $15M on Dec 17, 2024, in health and wellness payment facilitation. Visit
- SignalRank Corporation: $11.55M on Dec 21, 2024, focusing on private market investments. Visit
- Usual Labs: $10M on Dec 23, 2024, transforming tokenized assets into stablecoins. Visit
- Tracer Biotechnologies: $10M on Dec 12, 2024, innovating in ctDNA assays. Visit
- Stipple Bio: $9.48M on Dec 20, 2024, enhancing cellular profiling. Visit
- Mindgard: $8M on Dec 20, 2024, securing AI systems. Visit
#Funding#UniversalMatter#InterCure#Atmo#Sitemate#Meddipay#SignalRank#UsualLabs#TracerBiotechnologies#StippleBio#Mindgard#Cannabis#AI#Technology#Health#Wellness#Software#Investments#Startups#Finance#Innovation