Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🎙*DinoWars*🦖 - Battle Royale built on blockchain, сwhich brings an opportunity to earn by playing without any pyramidal basis
What do I already know about the project: 👇
1️⃣Upcoming announce of launch at more than 20+ launchpads
2️⃣Attracted the attention of DAO Maker and received an invitation to run with them
3️⃣Preparing listing at ByBit
4️⃣The community is so crazy that they get tattoos with characters from the game
5️⃣Launch of the game is very soon (I’ve already seen the insides)
6️⃣Now they've started to actively swing, preparing contests (with cash prizes) and some major movement
(Your opinion on the game )
TG DinoWars | Чат DinoWars
#Dinowars#Bybit#Daomaker
🎙 INVEST REPORT ANNOUNCE YOUR AI
⚖️ INVEST REPORT project rating 9/10 ⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
YOUR AI Protocol is the world's first AI-driven content layer for e-commerce built on Bitcoin and Solana, empowering brands and creators to earn $YOUR and monetise content and maintain ownership.
Project now is IDO on DAO maker with 231x oversubscribed. Project is very HYPED with partners like Dao maker, Shopify, Gotbit hedge funds, Befi Labs, Genblock Capital and 30 others.
⚙️ What makes YOUR AI Protocol ($YOURAI) unique?
📌AI Personalisation engine.
📌Streaming dynamic and personalised product content
📌Using the power of the crowd to explode the relevance and quality of online product content.
⚙️ Token details
- Token price: 0.01
- Token Unlocks: 30% TGE, 1 month cliff and then year linear unlocks
- Ticker: YOURAI
- Blockhain Network: Solana
- Token Supply: 1,000,000,000
- Initial Mcap: 275,000$
⚙️ Follow YOUR AI Media:
- Website: https://your.io/token
- Discord: https://discord.com/invite/8deTbfAsdW
- Twitter: https://twitter.com/yourtokens
- More Info: https://your.io/about-us
#YOURAI#DAOMAKER#IDO
🎙INVEST REPORT announce Lynex
The Native Liquidity Layer and ALM marketplace of Linea.
Lynex stands as a groundbreaking decentralized exchange (DEX) and liquidity marketplace on the Linea blockchain. It's a hub where users and DAOs can engage in a variety of actions within our dynamic protocol ecosystem. Lynex allows for token swapping, earning $LYNX as a liquidity provider, receiving voter bribes, and influencing the direction of emissions to maximize trading revenue.
🌟 Major Lynex launch dates are set! A thrilling chapter begins, and we're buzzing for the journey ahead.
⏰ Mark these milestones:
Daomaker IDO: 7th
Decubate IDO & Exclusive Lynex IDO: 12th
- TGE and Epoch 0: 15th
- Epoch 1 & Liquidity Mining: 22nd
- Community Airdrop: Late February
- Then a wave of Partner Integrations 🔥
More information:https://lynex.gitbook.io/lynex-docs/protocol-overview/about-lynex
⭐️Research
- Ticker: LYNX
- Blockhain Network: LINEA
- SHO tokens network: LINEA
- Token Supply: 100,000,000
- Initial Market Cap: $421,500
- Hard Cap: $1,287,500
BUY NOW: https://app.daomaker.com/project/hk9D1dBDqS
Follow Lynex media news to get information first one.
- Website: https://www.lynex.fi/
- Twitter: https://twitter.com/LynexFi
- Telegram chat: https://twitter.com/LynexFi
#Lynex#crypto#Listing#DAOMAKER
🎙DINOWARS MOON SHEET announcement
What do I already know about the project: 👇
1️⃣Upcoming announce of launch at more than 20+ launchpads
2️⃣Attracted the attention of DAO Maker and received an invitation to run with them
3️⃣Preparing listing at ByBit
4️⃣The community is so crazy that they get tattoos with characters from the game
5️⃣Launch of the game is very soon (I’ve already seen the insides)
6️⃣Now they've started to actively swing, preparing contests (with cash prizes) and some major movement
✅About DINOWARS token metric
- Token name: #DINV
- IDO price: 0,25$
- Initial price: 0,4$
- Total Supply: 50,000,000 $DINV
- Listing: July - August
👉 JOIN NOW
#DINOWAR#DINV#IDO#Listing#DAOMAKER#Pinkasale#BYBIT#Fundraising
🚨 SIGNAL TGE • MAY 2026 🚨
EdgeMarket is entering the next phase.
$SIGNAL will power the liquidity layer behind a new generation of AI validated prediction infrastructure.
This is not just another token launch.
This is the activation of decentralised truth validation infrastructure.
⚡ Launching with DAO Maker
EdgeMarket has secured a DAO Maker launchpad partnership, aligning with one of Web3’s strongest distribution and community ecosystems.
Designed for:
• High quality participant onboarding
• Long term ecosystem alignment
• Structured and credible market entry
What $SIGNAL powers:
• Liquidity infrastructure on BNB Chain
• Market participation and pricing
• The bridge between prediction, validation, and settlement
• Core infrastructure within the EdgeMarket dual layer architecture
EdgeMarket System:
🔶 $SIGNAL on BNB
Liquidity • Markets • Settlement
🔵 BETON on TON
Validation • Reputation • Truth Consensus
How the network evolves:
• Markets generate signals
• Validators verify outcomes
• Reputation strengthens through accuracy
• Truth becomes scalable infrastructure
No hype driven mechanics.
No manipulated narratives.
No centralised gatekeepers.
Only:
Conviction.
Validation.
Results.
📅 DAO Maker Launchpad — May 30 2026
📅 $SIGNAL TGE — May 30 2026
🌐https://edgemarket.ai/bnb/tokenomics
Prediction becomes intelligence.
Edge is earned.
#EdgeMarket#SIGNAL#DAOmaker#BNBChain#TON#AI#Web3#PredictionMarkets#Crypto#DecentralizedAI#TruthValidation#CollectiveIntelligence#Blockchain#TGE#Launchpad