Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
After falling from the support level of $500.0, #BinanceCoin reached the support level of $400.0 and recovered and is now trading above both levels.
As you can see in the chart, a dynamic resistance still prevents #BNBUSDT growth, so in the first step, crossing and breaking this resistance can be a sign of the continuation of the upward trend in the daily time frame.
So far, BNBUSDT has hit the dynamic resistance 2 times and failed to break it, these collisions may reach up to 5 times and then the price will start to grow. The current price movement scenario is between the $400.0 support and the dynamic resistance.
Easily earn a small income, Tencent PP Ranch Golden Egg Picking Guide!
Dear QQ Ranch friends, today, we are going to share how to easily make money in Tencent PP Ranch by picking up golden eggs! Just a few steps to make your virtual farm more abundant, earn money now!
————————
📚 1. Understand how to get golden eggs
First of all, golden eggs are a rare resource in QQ Ranch, which are picked up by participating in daily activities, completing tasks or within a specific time period. Remember to go online regularly to ensure that you don’t miss them!
📚 2. Improve the efficiency of picking eggs
⦁ Reasonable time arrangement: Choose the peak period of popularity to enter the game, and the chance of getting golden eggs is greater.
⦁ Add friends: help other players and share the experience and skills of picking eggs.
📚 3. Trade with golden eggs
The golden eggs you pick up can be sold through the in-game trading system to get game coins or other rewards. Pay attention to market trends, choose the best time to make a move, and maximize your profits!
📚 4. Participate in activities to get more rewards
Regularly participate in various activities of Tencent PP Ranch, and there will often be extra golden egg rewards to increase your small treasury. Pay attention to game announcements and participate in time!
📚 5. Continue to invest and enjoy the fun
Persist in going online every day, enjoy the fun of picking golden eggs, accumulate wealth, and make more like-minded friends.
————————
Come and pick up golden eggs at Tencent PP Ranch and earn your wealth! Perseverance, simple earning, and a promising future! 🎉
If you have other successful experiences in picking golden eggs, please share them in the comment area! I wish you all a happy game and full profits!
https://t.me/TencentPPRanch_bot/ppp?startapp=477789
#Bitcoin#Ethereum#BinanceCoin#Tether#XRP
#CorporateSocialResponsibility
#EmergingMarkets#Cardano#Solana
#CrossCulturalBusinessPractices
#Tencent PP Ranch
#Tencent PP Ranch Registration
#Tencent PP Ranch Official
#Free to play
#Free benefits
Tencent PP Ranch is an online simulation experience of ranch management game developed by Tencent. The initial version can give you the experience of adopting robot chickens, laying eggs, grabbing eggs, and stealing eggs, allowing you to relax through the game during a busy day. "Each egg obtained has a corresponding value"
🛒Official exclusive customer service telegram:
1️⃣t.me/TPR_005
2️⃣t.me/TPR_003
#Ethereum#Bitcoin#BinanceCoin#Tether#XRP#Cardano#Solana#Dogecoin#Polkadot#Chainlink
#ENJ#ICP#XTZ#UNI#XLM#MATIC
#Free rewards#Free community creation#Tencent PP Ranch Customer Service#Tencent PP Ranch Cooperation
#Free USDT withdrawals
#Free game resources