Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#Celsius Network further deposited 34.09M $MATIC ($25.7M) to #Binance in the past 10 hours.
In the past 2 days, Celsius Network has deposited 56.8M $MATIC ($44.5M) to Binance at $0.784 on average.
For more updates on Celsius Network, follow @spotonchain now and turn on your 🔔 at: https://platform.spotonchain.ai/en/entity/102
#Celsius Network returned to deposit 8,091 $ETH ($24.45M) to #Coinbase at ~$3,022 9hrs ago.
Notably, this is Celsius’ largest ETH deposit in the past 3 months. Previously, between Nov-13-23 and Jan-31-24, Celsius Network transferred 847,626 $ETH (~$1.90B) to FalconX, Coinbase, OKX, and Paxos, allegedly for some OTC deals.
Follow @spotonchain and visit the #Celsius Network at https://platform.spotonchain.ai/en/platform/entity/102?tokens=ETH&min_amount=9
In the past 2 days, #Celsius further deposited 67,500 $ETH ($156.5M) to #Coinbase Prime.
Overall, Celsius Network has moved 847,626 $ETH (~$1.90B) to CEX since November 13, 2023. Some of these ETH tokens might have been absorbed by whales via an alleged OTC deal.
Today, Celsius announced the distribution of over $3 billion in crypto and fiat to creditors has begun!
👉 Entity: https://platform.spotonchain.ai/en/platform/entity/102
#Celsius Network deposited 25.75M $MATIC ($21.26M) to CEX at $0.826 on avg in the past 8 hours:
• 22.73M $MATIC ($18.79M) to #Binance
• 3.02M $MATIC ($2.47M) to #Crypto.com
Currently, Celsius Network still holds 34.09M $MATIC ($27.56M) in the address.
To know when they move out $MATIC again, follow @spotonchain and turn on your 🔔 at: https://platform.spotonchain.ai/en/entity/102
🚨🚨#Celsius Network deposited 11,300 $ETH ($24.9M) to #Coinbase and #FalconX ~5hrs ago, as the $ETH price recovers.
Notably, in the past 4 days, Celsius Network has further deposited 48,200 $ETH ($108M, avg price: $2,240) to Coinbase and FalconX.
👉 More details: https://platform.spotonchain.ai/en/signal-details/celsius-network-deposited-eth-to-falconx-and-coinbase-13503
Two institutions #Celsius and #FTX moved out a total of $59.06M in 6 assets to CEX in the past 8 hours!
1. Celsius further moved 22,500 $ETH ($50.78M) to #Coinbase at $2,257 ~8 hours ago.
➡️ Now, Celsius only holds around 39,969 $ETH ($90.9M) in address 0xdb3.
👉 More details here
2. FTX and Alameda Research moved out $8.28M in 6 assets, including $ETH, $OKB, $MTL, $PROM, $YFII, and $CREAM in the past 2 hours.
➡️ Overall, FTX and Alameda Research have moved out $707M worth of 91 tokens since October 24, 2023.
👉 More details here
Want to be updated with latest whale movements? Follow @spotonchain and visit us via https://platform.spotonchain.ai/en
🚨🚨 Note that both #FTX and #Celsius Network transferred $ETH out in the past hour:
1. #FTX 0xe39 transferred 1,500 $ETH ($3.09M) to Wintermute Trading:
- The FTX and Alameda addresses also moved out 7.64M MATIC ($5.74M), which may be deposited to exchanges soon.
👉 More details: https://platform.spotonchain.ai/signal-details/ftx-and-alameda-research-moved-eth-and-matic-out-8514
2. Celsius Network further transferred 5,000 $ETH ($10.3M) to middle addresses:
- In total, Celsius Network has transferred out 15,167 $ETH ($31.1M) in the past 15 days, after the price rose. Among them, 10,167 $ETH ($20.8M) have been deposited to #FalconX at an average price of $2,051.
👉 More details: https://platform.spotonchain.ai/signal-details/celsius-network-may-further-deposit-eth-to-exchange-soon-8504
✅ Check out the full signals and set alerts for the FTX, Alameda, and Celsius Network with us now!
🚢Celsius усиливает СПГ-флот новым заказом на верфи Samsung Heavy.
Датская Celsius Tankers (часть Celsius Shipping) связана с новым заказом на два СПГ-танкера вместимостью по 180 000 куб. м на верфи Samsung Heavy Industries.
Контракт оценивается примерно в $514 млн, с поставкой до сентября 2028 года.
Сделка продолжает серию заказов компании и расширяет её портфель СПГ-судов, который уже насчитывает около 24 единиц (в эксплуатации и на стадии строительства).
С операционной точки зрения, компания усиливает позиции в сегменте СПГ (LNG) на фоне устойчивого спроса на газ и долгосрочных контрактов, обеспечивающих загрузку флота.
Для рынка это подтверждает высокий интерес к СПГ-новострою и ограниченность слотов на корейских верфях, что поддерживает стоимость судов.
📌Celsius Shipping ApS — основана в Дании, частная судоходная компания, специализируется на СПГ-перевозках; принадлежит предпринимателю Кристоферу Бисгаарду (Christoffer Bisgaard).
#LNG#Shipping#Tankers#Shipbuilding#Celsius
🚨 As predicted, #Celsius Network further deposited 9,600 $ETH ($19.5M) to #Coinbase and #OKX via address 0xc45 ~3hrs ago.
In total, Celsius Network has deposited 19,160 $ETH ($40.31M) to #FalconX, #Coinbase and #OKX at an average price of $2,040 in the past 16 days.
Currently, Celsius Network still allegedly holds around 59,581 $ETH ($121M) across multiple addresses.
👉 More details: https://platform.spotonchain.ai/signal-details/celsius-network-further-deposited-eth-to-exchanges-8736
🚨 Both #FTX and #Celsius transferred out $ETH after the $ETH price crossed $2,300 again today!
1. #Celsius Network deposited 7,500 $ETH ($17.4M) to #FalconX ~ 8hrs ago.
- Total deposited amount in past 7 days: 25,000 $ETH ($57M).
2. #FTX moved 1,593 $ETH ($3.66M) to address 0xCeF ~55 mins ago.
- Address 0xCeF currently holds 2,244 $ETH ($5.16M) and may deposit $ETH to #Coinbase soon.
👉 More details: https://platform.spotonchain.ai/en/token?name=ETH
🚨🚨 Institutions and whale are depositing $ETH to exchanges!
1. #Alameda (#FTX) and #Celsius Network deposited a total of 17,603 $ETH ($39.5M) to #Coinbase in the past 11 hours.
- Among them, 9,603 $ETH ($21.6M) were deposited to the exchange around the recent local peak!
2. Smart whale 0xebf returned after 5 months of inactivity and deposited 6,000 $ETH ($13.5M) to #Binance just now.
- Currently, the whale still holds 6,127 $ETH ($13.8M) and has an estimated total profit of $17M (+69.5%) from $ETH, of which $10.7M has been realized!
👉 More details: https://platform.spotonchain.ai/en/token?name=ETH