Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⚡️TapSwap Community: Upcoming Exciting Developments
#TapSwap#Web3Gaming
The TapSwap Community announces upcoming major platform updates, new gameplay reveals, and a fresh phase for $TAPS. These developments are expected in the coming weeks.
Source: link
@tonlines
🔋Amazing to see our founder connecting with industry legends and innovators at the Real Games, Real Rewards event!
⭐️Excited about the insights and collaborations that will power the future of gaming and Web3.
🤝Big thanks to @gate_ventures, @Metadomo, and @Moxyio for making this event possible!
#CyberCharge#Web3Gaming
Like👍, Retweet🔵, Comment
Link to the Tweet!
🔗Tweet From Our Co-Founder: Read
Open Metaverse Podcast Features Catizen Co-Founder
#gaming#web3gaming
Catizen Announcement introduces a new episode of the Open Metaverse Podcast featuring Ricky Wong, co-founder and CFO of Catizen. The discussion covers his transition from auditor to Web3 entrepreneur and insights into building a gaming ecosystem.
Source: link
@tonlines
⚡️Catizen Announcement: Strategic Partnership with Animoca Brands
#TON#Web3Gaming#Catizen
Catizen Announcement reveals a strategic partnership with Animoca Brands, enhancing their position as a leading Telegram Mini App game on TON. With a user base of over 40 million and 30 million CATI tokens utilized, Catizen is dedicated to developing a robust Web3 ecosystem around gaming, tokens, and Mini Apps.
Source: link
@tonlines
🎮 Exciting News! Dive into the world of NotCoin, the biggest Web3 game! 🌐🚀 Unleash your gaming prowess, explore virtual realms, and earn real rewards. 💰🕹 Join the revolution now!
👉 Explore the limitless possibilities: https://t.me/notcoin_bot?start=r_577856_2232895🎮🌟#NotCoin#Web3Gaming
🎮 Exciting News! Dive into the world of NotCoin, the biggest Web3 game! 🌐🚀 Unleash your gaming prowess, explore virtual realms, and earn real rewards. 💰🕹 Join the revolution now!
👉 Explore the limitless possibilities: https://t.me/notcoin_bot?start=r_577856_2232895🎮🌟#NotCoin#Web3Gaming
🎮 Exciting News! Dive into the world of NotCoin, the biggest Web3 game! 🌐🚀 Unleash your gaming prowess, explore virtual realms, and earn real rewards. 💰🕹 Join the revolution now!
👉 Explore the limitless possibilities: https://t.me/notcoin_bot?start=r_577856_2232895🎮🌟#NotCoin#Web3Gaming
TapSwap Community: Share Your Ideas for the Beta
#TapSwapBeta#Web3Gaming
TapSwap is inviting community members to contribute ideas for their beta version. Participants can suggest game ideas, features to test, or provide feedback on existing elements. Successful ideas may be implemented in the final release.
Source: link
@tonlines
🤝UXLINK x @TOKYOBEAST_JP: 日本コミュニティパートナーシップ発表! 🇯🇵
UXLINKは、TOKYOBEASTと日本コミュニティパートナーシップを締結しました! 🎉
TOKYOBEASTは、ゲーム・クリプト・予想を融合させた革新的なWeb3エンターテインメントプロジェクトです。
💰 2,000万ドルの開発予算 & 業界のプロ80名が手掛けるこのプロジェクトは、数百万のWeb2ユーザーをWeb3へとスムーズに導きます。
このパートナーシップを通じて、UXLINKは日本のWeb3コミュニティの成長と発展を支援し、より多くのユーザーにこの革新的な体験を届けます!
一緒にWeb3の未来を創りましょう!
🤝UXLINK x @TOKYOBEAST_EN: Japan Community Partnership Announcement! 🇯🇵
We’re excited to announce our Japan Community Partnership with TOKYOBEAST, a cutting-edge Web3 entertainment ecosystem that fuses gaming, crypto, and prediction like never before!
With a $20M development budget and a team of 80 industry experts, TOKYOBEAST is set to attract millions of Web2 users and seamlessly transition them into Web3.
Through this partnership, UXLINK will help grow and engage the Japanese Web3 community, connecting users to this revolutionary gaming experience.
Stay tuned for more updates as we expand the Web3 community together! #UXLINK#TOKYOBEAST#Web3Gaming
🚀 Big Announcement - Snapshot Completed!
🎉 The snapshot for the Tycoon Airdrop was successfully completed at 14:00 UTC, Nov 17!
The qualified participants list is ready, based on the previously announced criteria.
📖 Review the details:
1️⃣ Tycoon Point calculation & mandatory conditions: https://t.me/singsingchannel/965
2️⃣ Eligibility criteria & conversion rate: https://t.me/singsingchannel/996
✨On Nov 18, we will reveal the qualified list along with the corresponding $SING amount you’ve earned⏰Specific claim time will be announced tomorrow (Nov 18). Stay tuned!
#SingSingAirdrop#Web3Gaming
https://x.com/d3vxr/status/2040642828703772992?s=46. Live demo of D3VXR beta:
DXR → gameplay → DXR rewards
End-to-end utility, working in real time.
No speculation — just execution.
Watch here 👇
d3vxr.app
⚡#D3VXR#GameFi#Web3Gaming
🚨 Big news!
🎮$SING is now integrated into our partner game - Chickizen!
From now on, you can enjoy Chickizen with even more options and flexibility. 🐥✨
💳 Payment just got easier, smoother, and more rewarding!
Dive in, play, and explore Chickizen like never before!
Easily buy $SING at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
- SingSing Mini App: https://t.me/SingSing_TG_bot/app?startapp=_wallet
- OKX Wallet: Guideline (https://t.me/singsingchannel/1088)
Play Chickizen with $SING: https://t.me/chickizenbot/app
#SingSing#Chickizen#Web3Gaming