Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce Our #BinanceLive AMA with BOSS || 5th January 2025 at ( 1:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 5th January , 2026 at (1:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Project Team
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉BOSS
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝Clarnium on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
⏰ Must Join " BOSS Social Media Links :
🌐Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with Stake Cash Coin(SACO) || 1st December, 2025 at ( 2:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 1st December , 2025 at (2:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Project Team
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉Stake Cash Coin(SACO)
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝Stake Cash Coin(SACO) on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/live/video?roomId=2285385
⏰ Must Join " Stake Cash Coin(SACO)" Social Media Links :
❌Twitter
✉️Telegram
🌐Website
📷Instagram
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with AIO protocol || 21th November , 2025 at ( 1:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 21th November , 2025 at (1:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Chloe & Jade
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉AIO protocol
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝AIO protocol on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2283711
⏰ Must Join " AIO protocol" Social Media Links :
❌Twitter
✉️Telegram
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with GIGGLE FUND || 16th November , 2025 at ( 6:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 16th November , 2025 at (6:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest :
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉GIGGLE FUND
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝GIGGLE FUND on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
⏰ Must Join " GIGGLE FUND" Social Media Links :
❌Twitter
🔥Website
✉️Telegram
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with Usd1swap || 13th November , 2025 at ( 1:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 13th November , 2025 at (1:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest :
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉Usd1swap
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝Usd1swap on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2283379
⏰ Must Join " Usd1swap" Social Media Links :
❌Twitter
🔥Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with MetaPi || 10th November , 2025 at ( 2:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 10th November , 2025 at (2:00PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Caitlyn
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉MetaPi
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝MetaPi on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2283001
⏰ Must Join " MetaPi" Social Media Links :
❌Twitter
🔥Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with MetaPi || 14th October , 2025 at ( 2:00 PM UTC)
🔠
🔠
🔠
🔠🔠🔠
🔠🔠
🔠🔠
⏳ Time : 14th October , 2025 at (2:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Caitlyn
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉MetaPi
✅Like & Retweet✅Twitter Post
✅ Follow
📝CryptoFight &
📝MetaPi on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/live/video?roomId=2280210
⏰ Must Join " MetaPi" Social Media Links :
❌Twitter🔥Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram✉️Channel
📝Twitter🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with Biokript-Bro || 09th October , 2025 at ( 3:00 PM UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 09th October , 2025 at (3:00 PM UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Adnan Alisic, CEO, Adnan_Biokript
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉Biokript-Bro
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝Biokript-Bro on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2280011
⏰ Must Join " Biokript-Bro" Social Media Links :
❌Twitter
✉️Telegram
🔥Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with "CDL" at 11th February 2025 at ( 4:PM, UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 11th February 2025 ( 4: PM, UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 50$ USDT
🤵♂️Guest : CDL Team
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉CDL
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝CDL on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2249344
⏰ Must Join "CDL" Social Media Links :
✉️Telegram
📝Twitter
🌐Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with "EvolveToken" at 3th February 2025 at ( 2:PM, UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 3th February 2025 ( 2:00 PM, UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Seth Founder Of Evolve
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉EvolveToken
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝EvolveToken on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2248252&utm_campaign=binance_live
⏰ Must Join "EvolveToken" Social Media Links :
✉️Telegram
📝Twitter
🌐Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with "StohnCoin" at 6th February 2025 at (3 PM, UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 6th February 2025 ( 3:00 PM, UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Ing. Jozef Libant - CEO / Brett Weigel - COO / Jason Stanley - CIO / Alexander Almkvist - CTO
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝StohnCoin on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2248211
⏰ Must Join "StohnCoin" Social Media Links :
📝Twitter
🌐Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight
⚠️
⚠️
⚠️
⚠️
⚠
🔔AMA ANNOUNCEMENT
🗣We are pleased to announce our #BinanceLive AMA with "POPG" at 21th February 2025 at ( 12 PM, UTC)
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
🔠
⏳ Time : 21th February 2025 ( 12 PM, UTC)
🏠 Venue
🔶Binance Live
💎 Reward : 100$ USDT
🤵♂️Guest : Petra Apostolovic - PR & Community and Gabriel Raimundi - Marketing
➡️There will be 3 segments. Last approximately for 45 minutes - 1 hours.
🟢Segment 1: Introduction Questions
🟢Segment 2: Twitter Questions
🟢Segment 3: Live Questions
📌Rules to follow AMA:
✅ Join
✉️CryptoFight
✉POPG
✅Like & Retweet
✅Twitter Post
✅ Follow
📝CryptoFight &
📝POPG on Twitter
📝 Ask Your Questions ( Here )
🔔 Set Reminder :
https://www.binance.com/en/live/video?roomId=2247598
⏰ Must Join "POPG" Social Media Links :
✉️Telegram
📝Twitter
🌐Website
⏰ Must JoinCrypto Fight Community :
✉️Telegram
✉️Channel
📝Twitter
🔶Binance Live
*️⃣Linktree
💥If You Want To Promote Your Project Or AMA Proposal
📞DM @Ryan_Fight