TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #65 · 8 апр.

Небольшой трик с регулярными выражениями который редко вижу в чужом коде. Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста. >>> 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

Резултати

Пронајдени 45 слични објави

Пребарај: #stopcholera

当前筛选 #stopcholera清除筛选

One of the ways cholera spreads quickly is through poor water storage. Ensure safe drinking water: Avoid consuming water from contaminated sources. Proper storage: Store drinking water in clean containers with tightly sealed lids. Treat water: If unsure about the safety of your water source, boil it or use a water purification method. #STOPcholera

Hashtags

Unsafe practices such as improper disposal of refuse and open defecation endanger the safety of water used for drinking and personal use. This rainy season: ✅Only consume water from safe sources ✅Stop open defaecation ✅Dispose of trash properly ✅Ensure proper drainage of sewage #STOPCholera

Hashtags

As the rainy season has started, ensure to practice proper environmental hygiene to prevent the spread of cholera at home and in your communities ❌Avoid open defaecation ✅Dispose of waste in designated areas ✅Keep sewers clear from refuse #StopCholera

Hashtags

Unsafe practices such as improper disposal of refuse & defaecating in open places put the safety of water used for drinking & personal use at risk. #STOPCholera, ensure to: ➡️Keep your environment clean ➡️Drink or use water that is boiled & stored safely ➡️STOP open defecation

Hashtags

#Cholera can spread through contaminated foods. Make your foods safe before consumption: ➡️PREPARE your food in a clean area, away from sewage or waste bins ➡️WASH fruits and vegetables properly with clean water ➡️STORE your food in well-covered containers ➡️COOK your food properly before eating ➡️USE water from safe sources #STOPcholera

UNCLEAN WATER, unwashed hands, and uncovered food are some of the ways #Cholera germs are spread. Ensure your water is safe before use: ➡️BOIL water before drinking ➡️USE water from safe sources ➡️STORE water in properly covered containers ➡️STOP open defecation #STOPCholera

ПретходнаСтраница 1 од 4Следна