Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Эксперты ВкусВилл дали комментарии об актуальном положении дел сети в сегменте растительных продуктов-аналогов, а также рассказали о планах по развитию категории “Вегетарианское» на 2023 года.
«С момента запуска продажи альтернативного мяса и колбасы выросли в 2 раза. Значительный рост продаж год к году наблюдается и в других категориях: молочная продукция (+38%), десерты (+70%), веганская кулинария (+65%).
В конце прошлого [2022] года мы решили оставить самый базовый ассортимент и заняться поиском и разработкой новых вкусов. При этом наши постоянные покупатели остались с нами, из чего сделали вывод, что к нам идут за классикой, и нам надо продолжать искать вкусы, которые станут любимым повседневным растительным продуктом.
Над новинками мы работаем на постоянной основе, чтобы радовать наших покупателей.
Этой весной порадуем на полках ВкусВилла появятся 2 сырокопченые веганские колбасы».
Читайте подробнее в статье 😉
@we_are_vkusvill#plantbased
High Protein Vegetable Patties
🥕 Ingredients:
- 1 small carrot 🥕
- 1 medium potato 🥔
- 1/2 bell pepper 🌶
- 1 onion 🧅
- 50 g soy granules 🌱
- 50 g corn 🌽
- 50 ml water 💧
- 100 g flour 🌾
- 1 tbsp starch ✨
- Oil for frying 🍳
Preparation:
1️⃣ Grate the carrot & potato, dice the pepper & onion, and place in a bowl 🥣
2️⃣ Soak the soybean granules in water, then add to the bowl along with the remaining ingredients and mix well 👩🍳
3️⃣ Shape the dough into patties and sauté in a pan with a little oil until golden brown 🥘
Enjoy! 😋
#HighProtein#VegetablePatties#VeganRecipe#HealthyEating#PlantBased
@dishes
High Protein Vegetable Patties
🥕 Ingredients:
- 1 small carrot 🥕
- 1 medium potato 🥔
- 1/2 bell pepper 🌶️
- 1 onion 🧅
- 50 g soy granules 🌱
- 50 g corn 🌽
- 50 ml water 💧
- 100 g flour 🌾
- 1 tbsp starch ✨
- Oil for frying 🍳
Preparation:
1️⃣ Grate the carrot & potato, dice the pepper & onion, and place in a bowl 🥣
2️⃣ Soak the soybean granules in water, then add to the bowl along with the remaining ingredients and mix well 👩🍳
3️⃣ Shape the dough into patties and sauté in a pan with a little oil until golden brown 🥘
Enjoy! 😋
#HighProtein#VegetablePatties#VeganRecipe#HealthyEating#PlantBased
@dishes
🌿Udon Noodle Bowl 🍜
Ingredients
• 🫒 Oil for frying
• 100 g smoked tofu 🧆
• 1/2 tsp chili 🌶
• 1/2 tsp thyme 🌱
• 1/2 tsp coriander 🌿
• 2 tbsp soy sauce 🍶
• 100 g mushrooms 🍄
• 2 cloves garlic 🧄
• 300 g udon noodles (pre-cooked) 🍜
Sauce:
• 1 tbsp paprika paste 🌶
• 2 tbsp agave syrup 🍯
• 5 tbsp soy sauce 🍶
• 200 ml water 💧
• 1 tbsp starch 🌽
• 1 tbsp white sesame 🥢
Side dishes for the bowl:
• 1 bok choy 🥬
• Red cabbage 🥬
• Cucumber 🥒
• Avocado 🥑
• Lime 🍈
• Spring onions 🧅
• Sesame seeds 🌱
• Paprika 🌶
Preparation:
1. 🔥 Fry the smoked tofu in oil, deglaze with soy sauce, season & set aside.
2. 🥄 Mix all the ingredients for the sauce together.
3. 🍄 Sear the mushrooms and garlic, deglaze with the sauce, and stir in the udon noodles.
4. 🍲 Fill the bowl with the udon noodles, tofu, and all the remaining ingredients.
#VeganRecipe🌱#UdonNoodles🍜#HealthyEats💚#AsianCuisine🍲#PlantBased
@dishes
🌿Udon Noodle Bowl 🍜
Ingredients
• 🫒 Oil for frying
• 100 g smoked tofu 🧆
• 1/2 tsp chili 🌶️
• 1/2 tsp thyme 🌱
• 1/2 tsp coriander 🌿
• 2 tbsp soy sauce 🍶
• 100 g mushrooms 🍄
• 2 cloves garlic 🧄
• 300 g udon noodles (pre-cooked) 🍜
Sauce:
• 1 tbsp paprika paste 🌶️
• 2 tbsp agave syrup 🍯
• 5 tbsp soy sauce 🍶
• 200 ml water 💧
• 1 tbsp starch 🌽
• 1 tbsp white sesame 🥢
Side dishes for the bowl:
• 1 bok choy 🥬
• Red cabbage 🥬
• Cucumber 🥒
• Avocado 🥑
• Lime 🍈
• Spring onions 🧅
• Sesame seeds 🌱
• Paprika 🌶️
Preparation:
1. 🔥 Fry the smoked tofu in oil, deglaze with soy sauce, season & set aside.
2. 🥄 Mix all the ingredients for the sauce together.
3. 🍄 Sear the mushrooms and garlic, deglaze with the sauce, and stir in the udon noodles.
4. 🍲 Fill the bowl with the udon noodles, tofu, and all the remaining ingredients.
#VeganRecipe🌱#UdonNoodles🍜#HealthyEats💚#AsianCuisine🍲#PlantBased
@dishes
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
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
🌾Oriental Mujaddara 🌾
🌾 Ingredients:
🍚 200g rice
🥫 1 can (300g) cooked brown lentils
🧴 Oil for frying
🧅 3 large white onions
🧅 2 red onions
🧂 Pinch of salt
🥄 150 ml vegetable stock powder
🌿 1 tsp cumin
🧂 Salt and pepper
🍃Yoghurt dip:
🥄 500g soy yogurt
🍋 Juice of half a lemon
🧂 1/2 tsp salt
🧄 2 cloves of garlic
🌿 1 bunch of chives
🌈Toppings:
🌿 Chives, 🍈 pomegranate seeds
#OrientalMujaddara#MiddleEasternFlavors#VeganRecipe#PlantBased#ComfortFood
@dishes