Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌟Thinking of applying for the IRAS scholarship?
Get insider tips from our current scholars to help with your application. ✍️ Don’t miss this opportunity to contribute meaningfully to Singapore’s economic and social growth. Apply to be an IRAS scholar at go.gov.sg/scholarapply by 31 March 2026.
#IRASscholarships#scholarships
Where tax builds tomorrow. 🇸🇬
Our scholars Nathaniel, Jing Rong, and Yern-Wei share about their journey in IRAS and how their work drives Singapore’s economic growth and inclusive society. Join us and discover diverse, purpose-driven careers that foster dynamic learning and collaborative innovation!
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
✍️ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where every expertise matters. 💼
At IRAS, we bring together different disciplines and unique specialists to work on projects that drives Singapore’s economic growth. IRAS scholarships are open to students from diverse areas of study.
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where tax builds tomorrow.💡
With pre-filled forms containing income details and tax reliefs, filing taxes is done in a matter of minutes. But what goes on behind-the-scenes to create this smooth taxpaying experience? Meet IRAS Director Leong Shi Wei, who leads multidisciplinary teams that oversee data policy, governance, and digital partnerships - making paying taxes a seamless and automated experience. Learn more about his work at IRAS here: https://go.gov.sg/iras-designing-the-tax-experience
Ready to collaborate with diverse teams on projects of national importance? 🇸🇬Apply to be an IRAS scholar today at go.gov.sg/scholarapply. Applications close on 31 Mar 2026.
#IRASscholarships#scholarships
Where every expertise matters.🧪
At IRAS, we bring together diverse and unique disciplines and specialists to drive projects that shape Singapore’s future. Meet Charmaine Tan, an IRAS scholar pursuing her Bachelor of Science in Life Sciences and Minor in Forensic Science, as she shares how her academic passion translates into meaningful impact.
Ready to put your expertise towards nation-building? 🌟 Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where growth knows no limits. 🌱
What does it mean to be an IRAS scholar? Meet Shaine Goh (Software Engineer, Infocomm Division) whose journey with the IRAS Merit Undergraduate Scholarship turned her potential into real-world impact. 💼 From computing skills to transforming tax services, Shaine shows how innovation can reshape the taxpayer experience. Read her story: go.gov.sg/iras-shaine-goh
At IRAS, we invest in your personal growth so you can maximise your full potential. Ready to grow without limits? ✨ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#scholarships#IRASscholarships
Where tax builds tomorrow.
IRAS scholarships are your gateway to a meaningful career that propels Singapore’s economic growth forward. Take your first step with us and unlock endless possibilities.
Ready to shape tomorrow? Learn more about life at IRAS at go.gov.sg/lifeatiras and visit go.gov.sg/scholarapply to apply to be an IRAS scholar via BrightSparks today.
#scholarships#IRASscholarships
🌐 As a Tax Director in IRAS’ Corporate Tax Division, IRAS scholar Joanne Tan refines tax laws and shapes policies that strengthen Singapore’s economic future, while leading a team of officers to discover the dynamic side of tax work. Learn more about her journey at IRAS here.
Apply for IRAS scholarships today at go.gov.sg/scholarapply
#lifeatIRAS#IRASscholarships#scholarships
Have questions about IRAS Scholarships? We’re here to answer them. 💬
Our scholarship application is now open, so don’t miss out! Apply today at go.gov.sg/scholarapply.
For more details, feel free to reach out to us at [email protected].
#IRASscholarships#scholarship#lifeatiras
📢 Calling all A-level/IB graduates and university students from all disciplines!
Catch a glimpse of life as an IRAS intern – follow our scholar Gerald Wong through his #dayinthelife.
Ready to make a difference? Join our future-ready #IRASFam and do work that matters in a collaborative, empowering environment. 🚀 Apply for IRAS scholarships at go.gov.sg/scholarapply or internships at www.careers.gov.sg today.
#lifeatIRAS#IRASscholarships