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

TGINSIGHT SIMILAR POSTS

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

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример). Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать? В Django по умолчанию есть готовая функция slugify для таких случаев. Но я её никогда не использую. Почему? Потому что её недостаточно! Приведём пример >>> from django.utils.text import slugify >>> slugify('This is a Title') 'this-is-a-title' Пока всё отлично >>> slugify('This is a "Title!"') 'this-is-a-title' Спец символы удалились, всё хорошо. >>> slugify('Это заголовок статьи') '' Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить >>> slugify('Это заголовок статьи', allow_unicode=True) 'это-заголовок-статьи' Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте. Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою. Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку: 🔸1. Исходный текст: >>> text = 'Мой заголовок №10 😁!' Взял специально посложней со специальными символами. 🔸2. Транслит Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги. from unidecode import unidecode >>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山") 'N S (r) u P 1/4 Yue Shan' Очень крутая библиотека, советую👍 В нашем случае получаем такое преобразование: >>> text = unidecode(text) >>> print(text) 'Moi zagolovok No. 10 !' Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы. А еще наш код уже поддерживает любой язык, будь то хинди или корейский. 🔸4. Фильтр символов Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона. >>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text) >>> print(text) 'Moi_zagolovok_No_10_' Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_". 🔸5. Slugify Осталось удалить лишние символы по краям и сделать нижний регистр >>> text = text.strip('_').lower() >>> print(text) 'moi_zagolovok_no_10' Получаем отличный slug! 😎 🌎 Полный код в виде функции. ______________ PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию. #libs#tricks#django

Резултати

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

Пребарај: #easyrecipes

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

@cookingdish · Post #610 · 11.12.2024 г., 15:35

MarryMeChicken🍗🍝 Ingredients: - 2 Chicken breast 🍗 - 1 Shallot onion 🧅 - 2 Garlic cloves 🧄 - 5 Sun-dried tomatoes 🍅 - 1 Serrano pepper 🌶 - Olive oil 🫒 - 1 tsp Lemon zest 🍋 - 1 cup Heavy cream 🥛 - 1 cup Chicken stock 🐓 - Fresh Basil sprig 🌿 - Dried Oregano 🍃 - Ground coriander 🌰 - Paprika 🌶 - Salt & pepper to taste 🧂 - Fresh parsley, chopped 🌱 - Linguine noodles 🍝 #CookingLove❤️#EasyRecipes#ComfortFood#CreamyChicken @dishes

Dishes.Cooking.Food

@cookingdish · Post #788 · 29.03.2025 г., 14:02

Potato Waffle Burger 🍔🥔 Ingredients: - 6 potatoes 🥔 - 70g all-purpose flour 🌾 - 100 ml plant drink 🥛 - 1 tsp salt 🧂 Toppings: - 2 spreads of vegan cream cheese 🧀 - 1 handful of lamb's lettuce 🥬 - 5 mushrooms 🍄 - Fried onions, chili 🌶 - Agave mustard dressing 🍯 Dressing: - 2 tbsp mustard - 3 tbsp agave syrup 🍯 - 1 tbsp oil 🫒 - 1 tbsp water 💧 - Pinch of salt, pepper 🧂 Preparation: 1. Grate the potatoes, squeeze out the liquid, and mix with all ingredients for the dough. 👩‍🍳🥔 2. Fry the mushrooms and season them. Mix the ingredients for the agave mustard dressing. 🍄 3. Pour the batter into the waffle iron. 🧇 4. Enjoy with the toppings! 😋 #PotatoWaffleBurger#VeganBurger#PlantBased#HealthyEats#EasyRecipes @dishes

Dishes.Cooking.Food

@cookingdish · Post #584 · 18.11.2024 г., 16:24

Potato Waffle Burger 🍔🥔 Ingredients: - 6 potatoes 🥔 - 70g all-purpose flour 🌾 - 100 ml plant drink 🥛 - 1 tsp salt 🧂 Toppings: - 2 spreads of vegan cream cheese 🧀 - 1 handful of lamb's lettuce 🥬 - 5 mushrooms 🍄 - Fried onions, chili 🌶️ - Agave mustard dressing 🍯 Dressing: - 2 tbsp mustard - 3 tbsp agave syrup 🍯 - 1 tbsp oil 🫒 - 1 tbsp water 💧 - Pinch of salt, pepper 🧂 Preparation: 1. Grate the potatoes, squeeze out the liquid, and mix with all ingredients for the dough. 👩‍🍳🥔 2. Fry the mushrooms and season them. Mix the ingredients for the agave mustard dressing. 🍄 3. Pour the batter into the waffle iron. 🧇 4. Enjoy with the toppings! 😋 #PotatoWaffleBurger#VeganBurger#PlantBased#HealthyEats#EasyRecipes @dishes

Dishes.Cooking.Food

@cookingdish · Post #604 · 05.12.2024 г., 15:50

Fillo Quiche Cups Recipe🥚🥓🧈 Perfect for brunch or appetizers! Ingredients: Fillo Dough Shells: 📜 250g Fillo pastry sheets 🧈 50g butter, melted Filling: 🥓 200g Pancetta or bacon, diced 🥚 10 Large eggs 🌿 50g Fresh chives, chopped 🧂 Salt/Pepper to taste 🧀 150g Swiss & Gruyere cheese 🧀 150g Fresh Mozzarella cheese, sliced ⚪️ Sesame seeds Instructions: 1️⃣ Preheat oven to 190°C (375°F). 2️⃣ Cut fillo sheets into squares, brush each layer with melted butter, and stack them in a muffin tin. 3️⃣ In a bowl, whisk eggs 🥚, add pancetta 🥓, chives 🌿, and cheese 🧀. Season with salt and pepper 🧂. 4️⃣ Pour mixture into fillo shells, top with mozzarella slices, and sprinkle sesame seeds ⚪️. 5️⃣ Bake for 15–20 minutes or until golden brown ✨. #EasyRecipes#BrunchGoals#MiniQuiches#CheeseLovers🥧 @dishes

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 #622 · 23.12.2024 г., 18:19

Chicken Wings with Grilled Caesar Salad🐔🥗🔥 Ingredients: - 5lb Chicken Wings 🍗 - Salt/Pepper to taste 🧂 - 1 Tsp Paprika 🌶️ - 1 Tbsp Poultry Seasoning 🌿 - 1/2 Tsp Cayenne Pepper 🌶️ - 1/4 cup Olive Oil 🫒 - 100g Grated Parmesan 🧀 - 150g Batter 🍞 - Fresh Dill 🌱 - 4 Cloves of Garlic 🧄 - 1 Romaine Lettuce 🥬 - Croutons 🥖 For Sauce: - 2 Tbsp Sour Cream 🥛 - 2 Tbsp Mayo 🥪 - 1 Branch of fresh dill 🌱 - 2 Tbsp Teriyaki Sauce 🍯 - 1 Clove of Garlic 🧄 #ChickenWings#CaesarSalad#GrilledGoodness#HomemadeMeals#EasyRecipes @dishes

Dishes.Cooking.Food

@cookingdish · Post #545 · 11.10.2024 г., 13:08

Spicy Tuna Cucumber Rolls ◇ Ingredients: 🍚Rice: - 1 Cup Premium Quality Short Grain or Sushi Style Rice - 1 Cup water - 1/4 Cup of Rice Vinegar - 1.5 Tbs of Sugar - 1 Tsp of Salt 🐟Spicy Tuna: - 1 Lb Sushi Grade Tuna Steak - 1/4 Cup Mayo - 1 1/2 Tbs Sriracha - 1 Tsp Sesame Oil - 1 Tbs Soy Sauce - Sesame Seeds - Finely Sliced Chives - Salt #SushiRecipe#SpicyTuna#JapaneseCuisine#FoodLovers#EasyRecipes🍣 @dishes

Dishes.Cooking.Food

@cookingdish · Post #592 · 25.11.2024 г., 14:18

Roasted Zucchini Pepper Pasta🍝🥒🌶️ Ingredients: 🥒 1 zucchini, grated 🌶️ 1 bell pepper 🧅 3 shallots 🧀 100 g cream cheese 🍁 40 ml maple syrup 🧂 1 tsp salt 🫒 Oil as desired 🌿 1 handful of parsley, chopped 🍝 250 g pasta Preparation: 1️⃣ Put zucchini, bell pepper, and onions in a casserole dish 🥘. 2️⃣ Add cream cheese 🧀, oil 🫒, maple syrup 🍁, and salt 🧂. 3️⃣ Roast everything in the oven for 35 minutes (top/bottom heat) 🔥. 4️⃣ Cook the pasta 🍝. 5️⃣ Mix the roasted vegetables, pasta, and parsley 🌿. Enjoy! 😋 #EasyRecipes#VegetarianPasta#RoastedVeggies#ZucchiniLovers#QuickMeals#ComfortFood @dishes

Dishes.Cooking.Food

@cookingdish · Post #602 · 03.12.2024 г., 15:28

Creamy Tuscan Chicken🍗🍅🌿 Ingredients: - 2 lb chicken breast 🍗 - Salt and pepper to taste 🧂 - 3 tablespoons flour 🌾 - 1 tbsp smoked paprika 🌶️ - 2 tablespoons butter 🧈 - 2 tablespoons olive oil 🫒 - 3 garlic cloves 🧄 - 2 shallots 🧅 - 1 sprig of cherry tomatoes 🍅 - 1/4 cup sundried tomatoes 🍅 - 1/4 cup parmesan cheese 🧀 - 1 teaspoon Italian oregano 🌿 - 1 cup chicken broth 🍲 - 1/2 cup white wine 🍷 - 2 cups heavy/whipped cream 🥛 - 2 cups fresh baby spinach 🥬 Steps: 1. Season chicken with salt, pepper, and smoked paprika. Coat with flour. 2. Heat butter and olive oil in a pan. Sear chicken until golden. Remove and set aside. 3. Sauté garlic, shallots, and cherry tomatoes in the same pan. Add sundried tomatoes. 4. Pour in white wine and chicken broth. Simmer and reduce. 5. Stir in heavy cream, parmesan, and oregano. Cook until thickened. 6. Add baby spinach. Return chicken to the pan and simmer until cooked through. Serve hot and enjoy! 🍴✨ #CreamyTuscanChicken#ChickenDinner#ComfortFood#TuscanFlavors#EasyRecipes#FoodLover @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 #600 · 02.12.2024 г., 15:51

Filet Mignon with Mushroom Sauce 🍷🍄 Ingredients: 🥩 1 Filet Mignon 🧂 Pinch of Salt 🫒 2 Tbsp Olive Oil 🧈 2 Tbsp Unsalted Butter 🧄 2 Cloves Garlic 🌿 1 Sprig Fresh Rosemary 🌱 2 Sprigs Fresh Thyme 🥦 Asparagus For the Mushroom Sauce: 🫒 Olive Oil 🧈 2 Tbsp Butter 🍄 100g Shiitake Mushrooms 🧅 1 Shallot Onion 🥃 1/4 Cup Bourbon 🥛 1 Cup Heavy Whipping Cream 🧂 Salt/Pepper #GourmetDinner#SteakNight#FoodieGoals#FiletMignon#MushroomSauce#FineDining#EasyRecipes @dishes

Dishes.Cooking.Food

@cookingdish · Post #615 · 17.12.2024 г., 17:19

Korean Kuksi 🍲 Ingredients: 🥩 500g Beef, thinly sliced 🍜 200g Wheat noodles 🧅 1/2 Onion, thinly sliced 🧄 2 cloves of Garlic, minced 🥒 1 Cucumber 🥗 1 Bunch of Radish 🥬 1/4 Cabbage 🍅 4 Tomatoes 🥚 4 Eggs 🌶️ Chilli powder to taste 🌿 1/2 Tsp Coriander 🧂 Salt/Pepper to taste 🫕 5 Tbsp Soy sauce 🍬 1 Tbsp Sugar 🥄 2 Tsp Sesame oil 🍋 1.5 Tsp Vinegar 🫛 1/4 cup Vegetable oil 💧 1 liter of cold Water ✨ Sesame seeds: for topping #KoreanKuksi#ColdNoodleSoup#AsianCuisine#KoreanFood#EasyRecipes#FoodLovers#FreshIngredients#CookingAtHome @dishes

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