Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#SC/USDT analysis :
#SC is currently experiencing a bearish trend, making new lows. The price is rejecting from the 200 EMA resistance, indicating a potential continuation of the downtrend. The price is expected to decline further, testing the swing low level.
TF : 1H
Entry : $0.003495
Target : $0.003225
SL : $0.003636
The Freely Eagle...
Oops Conditons Applied.
what's life ?
Happines today in journey, there might be a Sad turn tomorrow.
Slipped if on that turn, just stand smile and move ahead.
That's what a life for me.
Oblivious about what's gonna happen fews day ahead, was enjoying his journey of life fully.
Like a free fierce Eagle at high above the Limit less sky.
Boards were going on, and he was blindfolded by the next twist waiting for him.
Someone was waiting to gain his love, in the mid of his boards.
who..? Some call her/him Danger, Dead end, life threatening, etc. But the Common name was
Cancer. Yes!!!
Was unknown about it and flying high in his journery of life. That turn came, was encountered too.
The moment he got to know. His wings were cut, and the Eagle was Caged.
All the dreams, aims, were shattered.
Like all his hopes were slaughtered.
Was Broken, hurted, and lost all the hopes.
Bacause, he was still and Fierce Eagle; but wiith conditions applied,
Who used to jump and Run, was now caged where he can just walk.
Who dreamt of many things, but was caged because he wasn't able to do of his wish,
But still, he dealed with it. Accepted the long life inprisonment of conditions applied.
If not the aims and dreams hi choosed, then
He went by making new dreams of he can.
If not sports and physical activities anymore
He went with Pen as his Passion.
Not the Happiness he used to dream of
But by happiness of bringing best of his words.
Yeah, it's my life like a caged bird now,
But if are caged by conditions or sort of same. It isn't mean you can't fly anymore.
Have faith and believe in you, and just have a take off with the cage of conditions with you above the Sky.
#sc
#review
#shortstory
@the_critpic_hunter
#SC/USDT analysis :
#Siacoin has broken out above the previous high with robust momentum and formed a higher high. The price is anticipated to sustain its bullish momentum and challenge new highs. Seek a pullback near the support zone to consider a long entry.
TF : 1H
Entry : $0.00465
Target : $0.00489
SL : $0.00451
#没用的外站信息
可能会被群友说是没用的外站信息,就合并到一起发了。
————
#SC#SecretCinema#站点公告
We have a new IRC channel that we actually control.
Server: irc.brokensphere.net:6697
Channel: #secretcinema
Use site nick especially if you require assistance.
Please don't use the #sc channel for assistance or help with your account as staff will no longer idle in this chat.
TLDR; SC 更换了 IRC 的域名。
————
#shazbat#站点公告
2024-02-25 - Webchat broken
As you might have noticed, the webchat is a bit broken. We are working on fixing it, but it might take some time.
If you want a good chat experience, join IRC (see the help pages).
TLDR; webchat 炸了,要聊天就来 IRC。
————
#ABN#站点免费
站免还剩 8 天+
————
#HeBits#站点免费
站免还剩 1 天+
————
#AcidLounge#站点公告
Hey all,
We had over 10 accounts that someone took advantage of maybe from stolen database from another site. These peeps have now lost there account.
So please don't use the same password as other sites maybe consider using Two Factor Authentication (2FA) which can be setup in your settings.
You can use an app like Authy
https://authy.com/what-is-2fa/
TLDR; 有人号被盗了,记得开 2FA。