Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Channel: GOLD SCALPING TRADING SIGNALS
Members: ~4.4K
💢 Username: @gold_scalping_tradings
Description:
We are the best in Day trading and SCALPING. Contact our admin for your investment and copy trading @Gold_scalping_admin
🏷 Tags: #crypto_fx_trading
#gold#forex#trading#scalping#signals
https://telegramchannels.me/channels/gold_scalping_tradings
Group: Pip Pro Trader Fx
Members: ~2.68K
💢 Username: @pip_pro_traderfx
Description:
Learn Forex trading with real-time signals. Master gold trading, day trading, and scalping with expert strategies and daily motivation. Join our community and start your journey to financial freedom
🏷 Tags: #crypto_fx_trading
#forex_trading#day_trading#scalping#forex_signals#gold_signals
https://telegramchannels.me/groups/pip_pro_traderfx
🪙$STORM Token: Rising Success in the Market
A week after the listing, the $STORM token draws an upward curve on the chart. Let's try to figure out what the growth is connected with and what awaits us in the near future.
Let us remind you that Storm Trade— is not just another trading platform, they are pioneers setting trends in the world of decentralized finance, providing a unique trading experience on the largest derivatives #DEX on the #TON network.
Roadmap and development of Storm Trade
⚡️Storm Trade V2
Adding new pairs and trading instruments such as commodities ( #crudeoil, #gold etc.) and currencies (#Forex) will open doors to new markets, increasing your ability to diversify your trading strategies.
⚡️ Significant reduction in time to open positions, fixed closing price and guaranteed execution of SL/TP orders will make the trading experience precise and efficient.
The next versions of the protocol (V3 and beyond) will feature 1-click trading and gas-free trading. This will make your trading not only efficient but also accessible, lowering entry barriers for beginners.
🏆SocialFi and Copy Trading
Trading doesn't have to be boring. With the introduction of copy trading, you will be able to not only trade, but also follow the best traders, copying their successful strategies. Leaderboards of the strongest will encourage traders to compete, achieving better results, and the functions for creating teams (squads) will help find like-minded people and trade together.
🔮Leveraged Prediction Markets
Traders will be able to bet on the outcomes of various events, including economic indicators and sports results, with the possibility of using leverage. This will increase potential profits while minimizing investments and will attract the attention of not only cryptocurrency traders, but also those who want to speculate on real events.
📈Options, Spot Trading and Limit Orders
The introduction of options will allow users to apply more flexible and advanced strategies. The ability to hed and work with volatility will be an important addition to the main trading instruments, attracting experienced traders.
Limit orders will allow traders to use more complex strategies such as #scalping or grid orders, which can be profitable in conditions of high market volatility. #StormTrade will provide users with tools to automate such strategies, making them more efficient.
🪄AI Trading
Artificial Intelligence in Action
The team began experimenting with the use of artificial intelligence developed by partners to participate in a hackathon, and conducted the first experience of implementing #AI in Storm Trade. The built-in AI proved itself to be effective, helping to find optimal entry and exit points, predict market movements, and minimize risks.
The full list of tools planned for implementation can be found here:
🔗Read the article
StormTrade | Bot | Chat | Channel