Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
STON.fi Celebrates Successful Event in Tbilisi
#TON#Tbilisi#TONCommunity
At the recent meet-up in Tbilisi, STON.fi brought together the TON community with passionate discussions and showcases of innovative projects. The event, co-hosted by TON Georgia, highlighted the diversity of voices contributing to the growth of the TON ecosystem.
Source: link
@tonlines
🎧⤴
💎 Telegram’s Crypto Bot Launches Fee-Free Coin Swaps – Best Rates on TON and Beyond!
Telegram’s popular Crypto Bot introduced a groundbreaking Swap feature, enabling seamless exchanges of cryptocurrencies, including TON, at optimal market prices with 0% commission. This new feature empowers users to swap tokens effortlessly, catering to the needs of both seasoned traders and beginners. As Telegram strengthens its ties with The Open Network (TON), this development marks a significant step towards making zero-fee crypto trading more accessible and user-friendly. TON, Telegram, and crypto swaps headline this exciting update.
Chorus:
Swap it, drop it, no fees, we poppin’,
Crypto bot’s live, TON fam’s watchin’.
Best market rates, yeah, that’s the notion,
Zero percent, ridin’ this motion.
Verse 1:
Telegram’s bot, now it’s all in play,
Swappin’ TON coins without delay.
Zero fees stack, in a major way,
Crypto’s here to stay, what more to say?
Swipe right, the trades ignite,
Swappin' at the best rates, day or night.
TON on deck, the moves in sight,
Crypto bot’s game changin’, feelin’ right.
Chorus:
Swap it, drop it, no fees, we poppin’,
Crypto bot’s live, TON fam’s watchin’.
Best market rates, yeah, that’s the notion,
Zero percent, ridin’ this motion.
Verse 2:
From TON to ETH or BTC, quick like a flash,
One tap on Telegram, and the coins clash.
Zero fees givin' more green in the stash,
Crypto bot’s hustle, bringin’ in cash.
Telegram links up with TON,
Best swaps, no cap, just get it done.
In the market, bots always on the run,
Swappin’ coins, and we're havin' fun.
Chorus:
Swap it, drop it, no fees, we poppin’,
Crypto bot’s live, TON fam’s watchin’.
Best market rates, yeah, that’s the notion,
Zero percent, ridin’ this motion.
Verse 3:
Telegram and TON, now we’re connectin’,
Coins on the move, the fam’s respectin’.
Best rates, zero fees, no second-guessin’,
Crypto's risin', it's impressin'.
Swap so quick, it’s like a race,
Crypto bot's here, savin' time and space.
TON's in the mix, the market’s embrace,
With zero fees, everyone finds their place.
Chorus:
Swap it, drop it, no fees, we poppin’,
Crypto bot’s live, TON fam’s watchin’.
Best market rates, yeah, that’s the notion,
Zero percent, ridin’ this motion.
Bridge:
TON in the mix, we set the tone,
Zero fees, we break the stone.
Crypto bot's king on this throne,
This is the future, watch it be known.
#TONCommunity#CryptoSwap#TON
#TONCryptoNewsRapStyle
🎧@toncoin_rap
🙏SBT ONTON in real time!
🔍 Our chat has a bot that monitors the emergence of new SBTs in real time — they appear instantly along with passwords!
❤️ No need to search for them in different chats anymore - just join our community and get valuable Soul Bound Tokens to your wallet, so that you can get a drop for them later!
🟣Claim your SBT ONTON now!
#TON#ONTON#SBT#Airdrop#Web3#TONCommunity