Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🏆 GuPay Team Cup – 2025 FIFA Club World Cup Edition is LIVE! ⚽️
Choose your team. Power it with every transaction.
From the pitch to the blockchain — this is where Web3 meets real-world passion. ⚽️
🗓 June 9 – July 15, 2025
Support 1 of 32 legendary clubs from the official 2025 FIFA Club World Cup, use GuPay, and help your squad rise to the top!
🎯 How to join:
1️⃣Pick your favorite club by filling out the registration form: link
2️⃣ Make transactions using GuPay throughout the tournament
3️⃣ Each transaction boosts your team’s total score on the leaderboard
🎁 $5,000 Prize Pool
The entire reward will be shared among users who joined the team with the highest total transaction volume via GuPay during the campaign.
📌 Fill the form now to lock in your team choice: link
📊 Team standings and leaderboard will be updated regularly — stay tuned!
🌐 From sport to spending, culture to crypto — Gumart is bringing Web3 to real life, one goal at a time.
#GuPayTeamCup#GuGiveaway
🏆 GuPay Team Cup – FIFA Vibes, $5,000 Prize Pool! 📈
Something big is coming to GuPay... and it’s dressed in jerseys, flags, and fire.✨
⚽️ 32 teams - inspired by the world of FIFA
💥 Fierce competition, full of national pride
💰A massive $5,000 prize pool waiting at the finish line
Choose your team. Make your moves.
Support your side and help them rise to the top.
Can you guess what’s coming? Stay tuned 👀
#GuPayTeamCup#GuGiveaway
🛍 GuPay Team Cup – Midway Update: Who’s Leading the Race?
It’s been nearly three weeks since the GuPay Team Cup kicked off - and the competition is getting intense! With thousands of Gumart residents rallying behind their favorite FIFA clubs, the blockchain scoreboard is anything but predictable. ⚽️💸
Here’s the current Top 4 (by GuPay transaction volume):
🥇 Real Madrid – Still leading with unstoppable momentum
🥈Chelsea – Not far behind, showing strong team spirit – A surprise rise from Africa
🏅Al Hilal SFC – Consistency and strategy paying off
🏅Manchester City – Still showing its strength
🎉Remember: $5,000 prize pool will be distributed to users who joined the team with the highest total GuPay transaction volume by the end of the tournament.
🚀 Don’t forget to:
✅ Register your team: link
✅ Transact with GuPay before July 15
✅ Watch the leaderboard change in real-time
From football fields to financial freedom — this is Web3 in action, where fans aren’t just cheering, they’re shaping the outcome. ✋
🏁 2 weeks left. One winner. Will it be your team?
#GuPayTeamCup#GuMinigame#FIFAClubWorldCup2025
🏆 GuPay Team Cup – The Race Is On! ⚽️
Just 3 days in, and over 2,000 Gumart residents have jumped into the GuPay Team Cup – 2025 FIFA Club World Cup Edition!🚀
🔥 The leaderboard is heating up:
1️⃣ Real Madrid is leading the charge
2️⃣ Chelsea right behind
3️⃣ Manchester City chasing hard!
Want your team to rise? 💥
👉 Every GuPay transaction boosts your team’s score and brings you closer to the $5,000 prize pool!
📍Choose your team now and start transacting: link
#GuPayTeamCup#GuGiveaway#FIFAClubWorldCup
‼10,000+ TRANSACTIONS IN 20 DAYS 🤑
GuPay Team Cup – FIFA Club World Cup 2025 is going global - and it’s powered by BNB Chain ⚡️
From Real Madrid to Man City, 32 legendary football clubs are battling it out. But this time, it's not just on the field — it's on-chain. 🏟
📣 Gumart is rewriting what mass adoption looks like:
10,000+ real-world transactions made through GuPay across hotels, stores, and events — all in less than 3 weeks.⬆️
🚀 Built on BNB Chain's trusted infrastructure, Gumart is leading the charge in making crypto usable, visible, and impactful in everyday life.
➖Want to join?
Pick your team and make transactions with GuPay. Help your squad rise to the top.
🌐 Be where culture, payments, and crypto collide.
#GuPayTeamCup#Gumart#BNBChain