Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 Ancient lake beds called "playa lakes" preserve natural records of Earth's past. Layers of sediment in these basins capture pollen, plant remains, and even insect fossils, revealing climate cycles and environmental shifts over thousands of years. Some dry lakebeds in the U.S. Southwest show records going back 120,000 years. ✨
#geology⚡#paleoclimate⚡#lakes
👉subscribe Interesting Planet
👉more Channels
🌍 Canada has more lakes than any other country, and many are so large they contain whole islands with their own lakes—making some islands-in-a-lake-on-an-island truly unique on Earth. ✨
#islands⚡#archipelago⚡#lakes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Africa’s Lake Victoria is the largest tropical lake in the world. Its outflow forms the start of the Nile River, which journeys over 6,600 kilometers north to the Mediterranean Sea. ✨
#lakes⚡#rivers⚡#Africa⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 The salt-loving halophiles of California’s pink Lake Hillier thrive where few others survive. These tiny microbes give the lake its vivid color by producing pigments that protect them from extreme salt and sunlight—turning the water a bubblegum pink! ✨
#microbes⚡#pigment⚡#lakes
👉subscribe Interesting Planet
🌍 Russia’s Lake Karachay is so contaminated from past nuclear waste that standing on its shore for just an hour could be fatal—one of the most polluted lakes on the planet. ✨
#rivers⚡#lakes⚡#pollution⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some lake water can take hundreds of years to fully circulate from the surface to the deepest layers and back again, creating slow, hidden water cycles that influence local climates and ecosystems. ✨
#hydrology⚡#lakes⚡#cycles⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some of the world’s oldest lakes, like Lake Ohrid in Europe, have existed for more than one million years, preserving unique species found nowhere else on Earth. ✨
#lakes⚡#biodiversity⚡#longevity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Siberia’s Lake Baikal freezes in winter, forming ice so clear that cracks and bubbles can be seen meters deep. In spring, melting ice creates musical sounds as it shifts and breaks apart. ✨
#lakes⚡#rivers⚡#Siberia⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Lake Titicaca, perched almost 3,812 meters above sea level, is the world’s highest navigable lake by large boats. Its clear waters straddle the border between Peru and Bolivia in the Andes. ✨
#lakes⚡#Andes⚡#altitude⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In Africa’s Lake Natron, minerals in the water turn it bright red during the dry season. The lake’s extreme chemistry preserves animal remains, creating eerie natural “statues.” ✨
#lakes⚡#Africa⚡#chemistry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The world’s clearest lake is Blue Lake in New Zealand. Its pure water is so transparent that objects can be seen up to 80 meters below the surface—almost like looking through glass. ✨
#lakes⚡#water⚡#clarity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Finland boasts about 188,000 lakes, earning it the nickname "Land of a Thousand Lakes." Many of these lakes were formed by retreating glaciers at the end of the last Ice Age. ✨
#lakes⚡#glaciation⚡#Finland⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels