Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
BNB Chain Cookbook: Winners Spotlight 🏆
Congrats to our BNB Chain Cookbook bounty winners! These examples help developers build smarter on BNB Chain.
👉 Submit your own to win a share of the $10K bounty:
https://bnbchain.org/en/hackathons/bnb-ai-hack#submityourexampletobnbchaincookbook
Meet the winners 👇
🔸 AI Trading Assistant Module by https://github.com/Maiga-AI
Boost BNB MCP with AI-powered trading tools. This module integrates OpenAI Tools to assist with blockchain analytics and trading, offering a robust example of advanced AI x blockchain synergy.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/98
🔸 Privy MPC Wallet Demo by https://github.com/mauridev777
Learn how to integrate Privy.io for MPC wallets that connect Web2 identities to Web3. This example demonstrates simplified user experiences without the need to manage private/public keys.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/97
🔸 BNB Testnet Faucet by https://github.com/mauridev777
Easily request tBNB on the testnet with this simple and user-friendly faucet interface. A helpful tool for devs testing on BNB Chain.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/95
🔸 Smart Contract Discord Notifications by https://github.com/mauridev777
Set up real-time Discord alerts for your smart contracts. This module provides a clean and structured way to notify users via Discord webhooks.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/93
The $10K Cookbook Bounty is still live. Why join?
✅ $100 - $1,000 reward per example
✅ Showcase your work on BNB Chain
✅ Grow visibility for your project
Get started:
1️⃣ Pick a topic or propose your own: https://bnbchain.org/en/hackathons/bnb-ai-hack#submityourexampletobnbchaincookbook
2️⃣ Submit your example: https://bnbchain.org/en/cookbook
3️⃣ Winners picked every 2 weeks.
Let’s build together on #BNBChain💛
BNB Chain Cookbook: Winners Spotlight 🏆
Congrats to our bounty winners! These examples help developers to build smarter on BNB Chain.
👉 Submit your own to win a share of the $10K bounty:
https://bnbchain.org/en/hackathons/bnb-ai-hack#submityourexampletobnbchaincookbook
Meet the winners 🧵👇
🔸 4EVERLAND Hosting MCP by https://github.com/furyGo
Deploy Greenfield projects via 4EVERLAND with the help of an AI assistant. This example shows how to automate deployment and simplify workflows.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/73
🔸AI Wallet Reputation NFT by https://github.com/VamshiVerma
A python-based demo that analyzes wallet behavior and issues NFT badges based on reputation. A strong use case for AI + Web3 identity.
Explore on Github: https://github.com/bnb-chain/example-hub/pull/32
The $10K Cookbook Bounty is still live.
Why join?
✅ $100 - $1,000 reward per example
✅ Showcase your work on BNB Chain
✅ Grow visibility for your project
Get started:
1️⃣ Pick a topic or propose your own: https://bnbchain.org/en/hackathons/bnb-ai-hack#submityourexampletobnbchaincookbook
2️⃣ Submit your example: https://bnbchain.org/en/cookbook
3️⃣ Winners picked every 2 weeks.
Let’s build together on #BNBChain💛
🚀 Calling all #BNBChain builders! Sign up for the BNB Chain Gas Grants Program and grab your share of $1M+ in rewards! 💸
If your project is on BSC/opBNB mainnet after Jan 1, 2024, with 100+ DAU & a security audit, this is your chance to grow! 🔥
Register now 👉https://wkf.ms/3M8Y6e7
🏆 Become a Champion Builder in the #BNBChain Q3 2024 Hackathon!
🚀 With a $500K+ prize pool, direct interviews with the MVB program, kickstart packages, and more, it's time to take your project to the next level!
Submit your project below 👇
https://dorahacks.io/hackathon/bnbhackathon-q3/detail
🔥Less than 1 gwei on BNBCHAIN via TokenPocket, around 10x cheaper!
To deliver a smoother trading experience, TokenPocket and BNBChain are teaming up to slash gas costs for users. #BNBChain
Trade on BNBChain, Trade on TokenPocket!
👉tp.xyz
🚀Instantly bridge your $SOL to $BNB with ease!
It's #BNBChain SZN! 🔥
Seamlessly bridge your assets and unlock new opportunities on BNBCHAIN. Fast, simple, and secure!
📱https://tokenpocket.pro
💻https://swap.transit.finance/
BNB Chain NFT achievements
🔸The cumulative number of NFTs minted on #BNBCHAIN has exceeded 100 million
🔸Developers have deployed a total of 24,839 NFT contracts on BNBChain
🔸BNBChain has processed 261 million NFT transfers.
🎉 Campaign Success!
We’re thrilled to wrap up TEARLINE x
@BNBChain
DappBay Campaign as part of the #BNBChain Featured Activity Series!
🔥 Key Results:
✅ 2,000+ participants engaged with daily check-ins!
✅ 12 MILLION Power Points distributed to 120 lucky winners! A massive THANK YOU to everyone who joined! 🙌 Stay tuned for more exciting updates and rewards.
👉 Explore BNB Chain’s latest campaigns: https://dappbay.bnbchain.org/campaign
BNBET Token Unlock — Official Update!
$BNBET token is now unlocked and distributed according to plan.Breakdown of allocation:
-2% locked again — long-term stability and trust
- 2% added to the bet pool wallet — to support liquidity and active betting markets
-1% allocated for marketing and development — to fund upcoming campaigns, partnerships, and growth initiatives.
This unlock is designed to strengthen liquidity, expand the ecosystem, and fuel ongoing development.
As we enter this next phase, all movements directly support the platform and its community-driven growth.
The build is continues.
$BNB #BNBChain