Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#ACM/USDT analysis :
#ACM is currently in a correction phase and is expected to retrace to test the 200 EMA before resuming its bearish momentum. However, the current level presents a good opportunity for long trade.
TF : 4H
Entry : $1.075
Target : $1.193
SL : $0.994
#ACM/USDT analysis :
#ACM is currently in a downtrend, with the price consistently trading below the 200 exponential moving average (EMA). Recent price action shows a rejection from the 200 EMA, suggesting a continuation of the downward momentum. As a result, it is expected that the price will decline further and test previous lows.
TF : 1D
Entry : $1.520
Target : $1.235
SL : $1.690
#ACM/USDT analysis :
#ACM is in a downtrend, trading below the 200 EMA. The price is currently retracing back to the 200 EMA and a resistance zone, and it is expected to decline from this point, continuing its bearish momentum to test lower levels. It is advisable to wait for a pullback for a short entry.
TF : 1H
Entry : $1.535
Target : $1.478
SL : $1.567
#ACM👈
Call given here
Hit 1667
Target 1 done ✅
14% profit
If you invested 1 btc it's now 1.14 btc now 🤑🤑
Signal before pump @ low level
Always trade with us for max profit 😊🤑💃
We are best pump tracker 🤑
#ACM#站免
ACM 五周年,站免两周。
Dear @everyone
We are absolutely thrilled to announce that we are celebrating the 5th anniversary of our beloved platform dedicated to the mesmerizing world of Asian cinema! 🥳🍾
It feels like just yesterday that we embarked on this incredible journey, passionate about bringing you the best of Asian cinema. Over the past five years, we've delved deep into the heart of cinematic artistry, exploring the rich tapestry of stories, cultures, and talents that make Asian cinema truly exceptional.
One of our core missions has always been to spread our love for Asian cinema around the globe and are very proud of what we have been able to accomplish so far. We've had the privilege of showcasing masterpieces, hidden gems, and emerging talents from across Asia. From the heartwarming dramas to the pulse-pounding action, the thought-provoking indie films to the visually stunning blockbusters, every frame has been a celebration of the cinematic excellence that defines Asian cinema.
To mark this momentous occasion, we have activated global FreeLeech (FL) for the next 2 weeks so you can finally download all those films you have bookmarked since our last global FL :). This celebration is not just about looking back but also about looking forward to the exciting cinematic adventures that await us.
None of this would have been possible without the unwavering support of our dedicated community. To each and every one of you who has shared their love for Asian cinema, contributed insightful discussions, and made this platform a vibrant hub – THANK YOU! Your enthusiasm fuels our passion, and we are incredibly grateful for your ongoing support.
As we raise a virtual toast to the past five years, we eagerly look forward to the next chapter. With your continued support, we are confident that the future holds even more exciting discoveries, cinematic treasures, and shared moments of joy.
Thank you for being a part of our cinematic journey. Here's to five years of Asian cinema magic, and to many more to come!
Cheers to the love of film! 🎉🎬✨
Yours,
AsianCinema Team