Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 In the Himalayas, the snow leopard’s wide, fur-covered paws act like natural snowshoes, distributing weight and keeping it from sinking on deep mountain snow. ✨
#wildlife⚡#adaptation⚡#Himalayas
👉subscribe Interesting Planet
🌎 The larva of the Himalayan glacier midge survives temperatures as low as -17°C by producing special proteins that act like antifreeze, preventing ice crystals from damaging its tissues. This adaptation lets it thrive in some of the coldest, highest places on Earth. ✨
#insects⚡#adaptation⚡#Himalayas
👉subscribe Interesting Planet
🌍 The Himalayas are rising by about 5 millimeters each year as the Indian and Eurasian plates continue to collide. This ongoing uplift makes these mountains among the youngest and fastest-growing on Earth. ✨
#mountains⚡#Himalayas⚡#tectonics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Bar-headed geese cross the Himalayas during migration, flying at altitudes above 7,000 meters. These birds have special hemoglobin that helps them absorb oxygen efficiently in thin air. Their migration route includes nonstop flights of up to 1,600 kilometers. ✨
#migration⚡#birds⚡#Himalayas
👉subscribe Interesting Planet
👉more Channels
🌎 In the soaring skies of the Himalayas, the bar-headed goose migrates over Mount Everest, flying at altitudes above 8,000 meters—higher than any other bird. Special hemoglobin in their blood enables them to absorb oxygen efficiently in the thin air, making this epic journey possible each year. ✨
#migration⚡#birds⚡#Himalayas
👉subscribe Interesting Planet
🌎 Mount Everest's border runs exactly along the Nepal-China divide, making its summit shared by two countries. Hikers can reach the top from either side, but the official border marker is a small metal pole embedded in the ice at 8,848 meters—the highest international boundary on Earth. ✨
#borders⚡#geography⚡#Himalayas
👉subscribe Interesting Planet
👉more Channels
🌍 The Eastern Himalayas are a biodiversity hotspot with over 10,000 plant species, and nearly a quarter of them are found nowhere else, despite covering less than 2% of India’s total area. ✨
#biodiversity⚡#Himalayas⚡#ecology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Kalapani region is a small Himalayan area claimed by both India and Nepal. Its strategic location at the tri-junction with China makes it a unique hotspot of geopolitical geography. ✨
#borders⚡#dispute⚡#Himalayas⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 High in the Himalayan valleys, the Himalayan blue poppy blooms with dazzling blue petals. Its color comes from unique pigments that protect it from intense ultraviolet sunlight found at high altitudes. ✨
#flowers⚡#adaptation⚡#Himalayas
👉subscribe Interesting Planet
🌍 In Himalayan valleys, local communities have revived ancient glacial water channels called "kuls" to guide meltwater for farming. These living systems adapt to changing ice and rainfall each year. ✨
#Himalayas⚡#adaptation⚡#irrigation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 The Himalayan honey bee builds its hives on high cliffs, crafting giant honeycombs and producing reddish honey with unique psychoactive properties prized by local tribes. ✨
#honeybee⚡#Himalayas⚡#nature
👉subscribe Interesting Planet
🌎 Some Himalayan glaciers are “surge glaciers,” moving up to 100 times faster than normal for short periods. These icy rivers can suddenly speed up, advancing kilometers in months instead of centuries—reshaping valleys with astonishing power. ✨
#glacier⚡#Himalayas⚡#earth
👉subscribe Interesting Planet