Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#FactFriday
Feeling thirsty is a late indicator of dehydration. To support optimal body function, it is important to drink water consistently throughout the day, even before thirst occurs. Staying adequately hydrated is essential for overall health.✅
#FactFriday#NCDCNigeria
🧼#FactFriday
Did you know? With proper hygiene, communicable diseases are preventable!
Washing your hands, keeping your environment clean, and practicing good personal hygiene can help stop the spread of infections.
Stay informed. Stay safe. #TakeResponsibility
What you eat matters more than you think.
✅Good nutrition fuels your body, strengthens your immune system, and helps you resist infections like flu, cholera, and other communicable diseases.
Healthy choices today, stronger immunity tomorrow.💪
#FactFriday#HealthyLiving#NCDCNigeria
#FactFriday
Contaminated water can spread illnesses which affects millions of people every year. Clean water and proper hygiene practices can greatly reduce health risks and improve wellbeing.
Protect yourself and your loved ones by:
✔️ Drinking only safe and clean water
✔️ Practicing good hand hygiene: Wash hands with soap under clean running water
✔️ Keeping your environment clean and free from waste
✔️ Following public health guidelines on sanitation
✨Your small daily actions can prevent big health problems.
Drink Clean, Stay Safe, Stay Healthy!
#FactFriday#HealthyLiving#NCDCNigeria
#FactFriday: _Powering your mind, even at rest! ✨_
🧠 Did you know your brain uses about 20% of your body’s energy even when you’re resting?
This energy keeps your brain cells active, helps process information, regulates your body systems, and keeps you alert.
💡 Take care of your brain with:
🍎 Proper nutrition
😴 Enough sleep
🧘 Regular self-care
Stay healthy, stay sharp!
#FactFriday#HealthyLiving#NCDCNigeria
#FactFriday
Drinking enough water daily helps you stay active, refreshed, and ready to take on the day. 💧
Small habits make a big difference! 💪
#FactFriday#HealthyLiving#NCDCNigeria
#FactFriday
Clean hands is one of the simplest and most effective ways to stay healthy and protect those around you from diseases👌
Washing your hands with soap under clean running water for just 20 seconds can reduce your risk of infection by up to 50%? 🙌🏽
Make handwashing a daily habit ✅️
#FactFriday#HandHygiene#HealthyLiving#NCDCNigeria
#FactFriday
Every year, mosquitoes are responsible for over 700,000 deaths by spreading diseases like malaria, dengue, and yellow fever.
💡 Protect yourself:
✅ Sleep under insecticide-treated nets
✅ Eliminate stagnant water around your home
✅ Use mosquito repellents
Small insect, Big threat.
Take action today!📌
#FactFriday#MosquitoFacts#NCDCNigeria
#FactFriday
Feeling better doesn’t mean the infection is gone.
Stopping antibiotics without proper guidance can fuel Antimicrobial Resistance (AMR) making infections harder to treat.
✔️Always follow your healthcare provider’s advice.
✔️ Only use antibiotics when prescribed
✔️ Always complete your dose
✔️ Take antibiotics exactly as prescribed
✔️ Don’t stop, skip, or share medications.
✅Your actions today protect your health tomorrow.!
#FactFriday#StopAMR#PublicHealth#NCDCNigeria
#FactFriday: Good Food, Good You!
🥬🥦Adding more fruits and vegetables to your meals can be a game changer for your health. They are filled with Vitamins, Minerals and fiber that helps boost your immunity, Protect your heart and lower the risk of chronic diseases.
Healthy eating starts with fruits and Vegetables✅️
#FactFriday#HealthyLiving#HealthyHabits#NCDCNigeria.
#FactFriday
💡 Did you know?
Not all bacteria are harmful. In fact, many are beneficial — helping your body digest food, absorb nutrients, and maintain a healthy immune system.
Understanding the role of good bacteria is key to making informed decisions about hygiene, antibiotics, and overall health.
#FactFriday#NCDCNigeria#TakeResponsibility#PublicHealthFacts
#FactFriday
💡With proper hygiene, safe practices, and protective measures, dangerous communicable diseases like Ebola can be prevented or controlled? 👐
Staying informed and taking responsibility keeps you and your community safe.
✔️ Practice good hygiene
✔️ Follow health guidelines
✔️ Stay alert and protect others
#TakeResponsibility#StaySafe#NCDCGov