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

Резултати

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

Пребарај: #seafoodlovers

当前筛选 #seafoodlovers清除筛选
Dishes.Cooking.Food

@cookingdish · Post #624 · 25.12.2024 г., 18:14

Grilled Salmon Steaks 🍣🔥 Recipe Here: Ingredients: 🐟 3 Fresh Salmon steaks 🍁 1/3 cup Maple syrup 🧂 Salt/Pepper to taste 🍋 Lime zest For the sauce: 🥛 1 1/2 Yogurt (plain) 🧄 1 clove of Garlic 🍋 1/2 Lemon (juice) 🫒 Olive oil 🍈 Pomegranate 🌿 Fresh herbs #GrilledSalmon#HealthyEating#SeafoodLovers#EasyRecipes#DinnerIdeas @dishes

Dishes.Cooking.Food

@cookingdish · Post #616 · 18.12.2024 г., 16:17

Grilled Octopus with Potato 🐙🥔 Ingredients: → Potatoes: 500g. Young Potatoes (mix of red and gold) 🥔 3 Tbsp Butter 🧈 1 Tsp Garlic Salt 🧄 Fresh Dill 🌿 → Octopus: 500g. Cooked Octopus 🐙 1/2 Shallot Onion 🧅 2 Tbsp Olive Oil 🫒 2 Tbsp Red Wine Vinegar 🍷 1 Tbsp Capers 🌱 Parsley 🌿 #GrilledOctopus#SeafoodLovers#PotatoRecipe#GourmetDish#CookingWithLove @dishes

Dishes.Cooking.Food

@cookingdish · Post #603 · 04.12.2024 г., 15:15

Coconut Shrimp Recipe🦐🥥 Ingredients: - 1 pound large raw pink shrimp 🦐 - 1 cup flour 🌾 - 2 eggs 🥚 - 1 cup panko breadcrumbs 🍞 - 1 cup grated coconut (unsweetened) 🥥 - 1 teaspoon salt 🧂 - 1/2 teaspoon garlic powder 🧄 - 1/4 teaspoon cayenne pepper 🌶️ - 1/2 lime zest 🍋 - Oil for frying 🛢️ For Sauce: - 1/4 cup sweet ginger chili sauce 🌶️🍯 - 1/4 cup apricot jam 🍑 #CoconutShrimp#SeafoodLovers#EasyRecipes#ShrimpRecipe#TropicalFlavors#FoodieFavorites @dishes

Dishes.Cooking.Food

@cookingdish · Post #593 · 26.11.2024 г., 16:18

🍽️Mussels in White Wine Garlic Sauce 🍷🧄 © Ingredients: 🦪 500g Fresh mussels 🫒 Olive oil 🍷 150ml White wine 🧅 1 Shallot onion 🧈 50g Unsalted butter 🌶️ 1/2 Serrano pepper 🍅 1 Branch of cherry tomatoes 🧄 2 Cloves of garlic 🌿 Fresh parsley 🍋 1/2 Lemon zest 🧂 Salt and black pepper to taste #SeafoodLovers#MusselsRecipe#WhiteWineSauce#GarlicLovers#EasyDinner#FoodieFavorites @dishes