Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#Liquidations🩸
🔴$630,000,000 IN LONG POSITIONS HAS BEEN LIQUIDATED IN THE PAST 60 MINUTES.
🔴According to CoinGlass data, In the past 24 hours, 355 972 traders were liquidated, the total liquidations comes in at $1.60 billion.
🔴The largest single liquidation order happened on Hyperliquid - ETH-USD value $13.38M.
#Liquidations🩸
🔴According to CoinGlass data, In the past 24 hours, 235 510 traders were liquidated, the total liquidations comes in at $1.04 billion.
🔴The largest single liquidation order happened on Hyperliquid - BTC-USD value $31.64M.
⚠️ Never invest more than you can afford to lose.
⚠️ High leverage increases risk — not profit.
⚠️ Don’t chase fast money: greed, FOMO, and impatience are your worst enemies.
⚠️ Breaking your own trading rules is the most dangerous mistake.
#Liquidations
$200 million liquidated from the cryptocurrency market in the past 1 hour.
-Never invest more than what you can afford to lose.
- Don't try to make quick money.
-High Leverage does not give you more money
-The most dangerous mistake is breaking your trading rules.
-FOMO, greed, impatience are the greatest trading enemies.
#Liquidations🩸
🔴In the past 24 hours , 92 275 traders were liquidated , the total liquidations comes in at $301.53 million
🔴The largest single liquidation order happened on Huobi - ETH-USD value $5.70M
⚠️ Never invest more than what you can afford to lose.
⚠️ Don't try to make quick money.
⚠️ High Leverage does not give you more money
#Liquidations
In the past 24 hours , 95 031 traders were liquidated , the total liquidations comes in at $236.84 million
The largest single liquidation order happened on Binance - ETHUSDT value $5.52M
* Never invest more than what you can afford to lose.
* Don't try to make quick money.
* High Leverage does not give you more money.
@Cryptomathh
Okay, here's an analysis of the ETH liquidation map suitable for Twitter, formatted in Markdown:
🚨#ETH Liquidation Map Analysis 🚨
Here's what the liquidation map tells us about potential price action. 👇
1️⃣Main Liquidation Zones: The BIGGEST liquidation cluster is concentrated AROUND & BELOW the current price (~$2626). Smaller clusters exist further below, around the 2500 to 2600 levels, while Long liquidations reside further above, between 2690 and 2712.
2️⃣Key Price Levels to Watch:
* Potential Support (Liquidation Zone): $2500-$2600 acts as strong support and bounce zone.
* Danger zone: 2626, current price is the biggest Liquidation cluster
* Resistance (Liquidation Zone): $2690 - $2712; push beyond here could trigger more long liquidations.
3️⃣Longs vs. Shorts: The image shows FAR more long liquidations than short liquidations which have already been cleared out. A HUGE cluster of longs is currently sitting under the current price, which can be liquidated.
4️⃣Potential Price Movements: Given the concentration of long liquidations below the current price, a move *DOWN* to trigger those liquidations seems more probable. 📉 Expect volatility around these liquidation zones!
5️⃣Key Takeaways for Traders:
* Be cautious of longing: Lots of longs sitting right at the current price could be liquidated.
* Anticipate volatility: Large liquidations can fuel price swings. Manage your risk accordingly!
* Watch key levels: $2500-$2600 as a potential support/bounce area and $2690-$2712 as potential resistance.
Disclaimer: This is just an analysis of liquidation data and not financial advice. Trade responsibly! #Crypto#Trading#Liquidations#ETHanalysis📊