Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⚡️Tonnel Network: Lower Fees with CryptoBot Integration
#CryptoBot#TON
Tonnel Network announces that the @CryptoBot team has reduced their fees, allowing deposits with just a 2% fee. The integration offers multiple new payment methods, enhancing user experience in the Tonnel Gift Marketplace.
Source: link
@tonlines
⚡️Tonnel Network Introduces New Payment Methods
#CryptoBot#Tonnel
The Tonnel Network has expanded its payment options in the Tonnel Gift Marketplace by integrating multiple methods through @CryptoBot. Users can now deposit various assets like BTC and SOL to increase their TON balance.
Source: link
@tonlines
👆 OMG! Would you look at that 👀
Reached 9th TP in just 6 hours in the VIP PRO channel!
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that our referral partners receive extra discounts, even cumulative with the special offer prices?
START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#tradingview#AItrading
👍 This is why we're here!
Reached 9th TP in just 7 hours in the VIP HTL channel!
With a 5% entry and a $1000 deposit, you could've earned $206!
ACCESS TO MANUAL TRADING for 70usdt/month
📊Dominate the market with Propheta AI Analyzer: AI uncovers hidden patterns with razor-sharp analysis, adapts on the fly with slick customization, and delivers next-level pair hunting — your edge for strategic supremacy! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#passiveincome#cryptobot#cryptochannel
Reached 9th TP in the VIP PRO channel!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Not sure? Considering? Contemplating? Come have a look at our performance reports, spend about5 minutes and see for yourself that everything is 100% legit! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#CryptoSignal#tradingview#cryptobot
Oops, we did it again 🤣
Reached 9th TP in the VIP HTL channel!
$203 in profits with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
💪Rule the market with Propheta AI Signals: ultra-sharp alerts, full-on process automation, and a killer Cornix synergy — your fast track to max profits! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#buyeth#cryptobot#AItrader
Reached 9th TP in the VIP HTL channel!
Easy $207 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 Join us and earn big!
Start here: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#cryptotrading#eth
Reached 9th TP in the VIP CLUB channel!
With a 5% entry and a $1000 deposit, you could've earned $456!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 OOooh yeah baby! And that's what we do every day! Every day milking those exchanges dry! Waiting for you: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingbot#cryptobot#passiveincome
👀 Well, would you look at that! 👆
Reached 9th TP in the VIP HTL channel!
$305 in profits with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
💰Turn data into gains with Propheta AI Analyzer: deep AI analysis spots trends with surgical precision, tweaks in seconds to your goals, and pair hunting pumps your trading to the next level — this is the evolution of the game! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#signalchannel#bitcoinnews
👀 Well, would you look at that! 👆
Reached 9th TP in just 1 day in the VIP PRO channel!
$609 in profits with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Love the profits you're seeing, but can't afford the VIP cost?
Earn over $40 per one recommendation with zero risk using our referral program!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptoexchange#cryptobot#autotrading
👀 Well, would you look at that! 👆
Reached 9th TP in the VIP PRO channel!
Using a 5% entry you could've earned $404 with a $1000 deposit
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
👉 Multiplying deposits every day!
Not convinced? Contact us for a free trial - @propheta_help
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#buyeth#cryptocurrency
Channel: Crypto Signals & Automated Trading Bot
Members: ~4K
💢 Username: @cryptosignalalert
Description:
Founded in 2017 - We provide high quality ALT COIN, Spot & Margin Signals, BTC Signals No of Trial/Free Signals Sent - 290 Success Ratio Of Trial/Free Signals - 100% We do provide Crypto Bot for Automated Trades Contact - @cripexperts for Premium Group
🏷 Tags: #crypto_fx_trading
#cryptosignal#automatedtrading#cryptobot#bitcoinbot
https://telegramchannels.me/channels/cryptosignalalert