Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🐈⬛NEW RELEASE
🐈⬛
🐈⬛Under Control Transforming Your Closed Guard by Brian Glick
🐈⬛
🐈⬛In Under Control: Transforming Your Closed Guard, Brian Glick delivers a complete system for building a closed guard that is tight, efficient, and relentlessly effective—regardless of size or strength
🐈⬛This is not a collection of random moves—it’s a carefully structured approach to controlling, breaking, and submitting opponents from one of jiu-jitsu’s most important positions.
$197
🐈⬛$14.99
🐈⬛
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#BrianGlick#Transitions#NoGi#NewWave
🐈⬛Buy
🐈⬛
😁See the Back Take The Back: Guard Passes To Back Takes by Giancarlo Bodoni😁
➡️See the Back, Take the Back: Guard Passes to Back Takes by Giancarlo Bodoni is the definitive blueprint for turning pressure passing into relentless back-taking offense.
➡️As a 2× ADCC champion, CJI standout, and one of the most technically disciplined athletes to emerge from the legendary Danaher system, Giancarlo has built his game around one thing: getting to the back and finishing—against everyone.
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#GiancarloBodoni#Transitions#NoGi#NewWave
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Take the Back from Closed Guard by Paul Schreiner😁
➡️Closed guard is one of the most powerful positions in Jiu-Jitsu — but many grapplers struggle to turn it into truly dominant finishes.
➡️Instead of relying only on sweeps or submissions, you’ll learn how to force reactions, break posture, and create openings that lead directly to back control — one of the most dominant positions in Brazilian Jiu-Jitsu.
$127😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#PaulSchreiner#Transitions#NoGi#IBJJF
💁♀️Buy
💁♀️
😁Jiu Jitsu For Old Guys: Entries For Over Under by Bernardo Faria😁
➡️Unlock the secrets to one of the most effective and accessible passing techniques in Brazilian Jiu-Jitsu with Jiu-Jitsu for Old Guys: Entries For Over Under by Bernardo Faria — 5x Black Belt World Champion, BJJ Fanatics Co-founder, and best-selling instructor.
➡️Designed specifically for older practitioners, this series emphasizes technique over athleticism, helping you maintain a competitive edge without relying on explosive power or speed
$197😍$19.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#BernardoFaria#Transitions#Gi#BjjFanatics
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Upper Lower Chains Links that Solve Problems Faster by Josh Saunders😁
➡️Unlock the secret to faster problem-solving and fluid movement on the mats with Upper Lower Chains Links that Solve Problems Faster, an innovative BJJ instructional by Josh Saunders — a 2x ADCC Trials winner and ADCC semifinalist.
➡️This groundbreaking approach empowers practitioners to adapt, innovate, and respond to challenges in real-time, making your game more dynamic and intuitive.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#JoshSaunders#Submissions#NoGi#Transitions
💁♀️Buy
💁♀️
😁Unpinable By Professor Henry Akins😁
➡️Henry shares the same principles passed down directly from Rickson Gracie—details rarely taught in modern academies—that turn crushing top pressure into an opportunity to escape, reset, and dominate the pace of the match.
➡️If you want a calm, technical escape system rooted in the deepest levels of Brazilian Jiu-Jitsu, Unpinable by Henry Akins will permanently change how you experience bottom position.
$279😍$24.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#HenryAkins#Transitions#NoGi#RicksonGracie
💁♀️Buy
💁♀️
😁Learning How To Relax In Jiu-Jitsu By Professor Henry Akins😁
➡️In Learning How to Relax in Jiu-Jitsu, legendary instructor Henry Akins reveals a groundbreaking approach to relaxation that transforms how you move, breathe, and apply technique on the mat.
➡️This course teaches you how to replace tension, panic, and wasted movement with structured breathing, intelligent pressure, precise timing, and effortless control
$279😍$24.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#HenryAkins#Transitions#NoGi#RicksonGracie
💁♀️Buy
💁♀️