Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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 Slovenia, the Postojna Cave harbors a rare blind amphibian called the olm, which can live without food for up to 10 years. The cave stretches over 24 kilometers and contains vast chambers, underground rivers, and prehistoric animal remains. ✨
#geology⚡#caves⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 Beneath Borneo’s limestone hills, the Clearwater Cave system spans over 237 kilometers, making it one of the world’s largest interconnected cave networks. Its underground river flows for 11 kilometers, supporting unique species like blind catfish and swiftlets that nest in its dark chambers. ✨
#caves⚡#geology⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 The world’s deepest cave, Veryovkina Cave in Georgia, plunges to 2,212 meters below the surface. Its vertical shafts, tight squeezes, and frigid underground streams challenge expert cavers. Specially adapted crustaceans and fungi live in total darkness at these extreme depths. ✨
#caves⚡#geology⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 In Croatia’s Velebit Mountains, the Lukina Jama–Trojama cave system plunges over 1,431 meters deep, housing rare leech species and tiny amphipods. Exploring these deep caves requires specialized rope techniques and careful study of underground water flows, revealing new life forms adapted to total darkness and isolation. ✨
#caves⚡#biodiversity⚡#geology
👉subscribe Interesting Planet
🌎 Deep beneath Venezuela, the Cueva del Fantasma cave is so massive that helicopters can fly inside. These vast underground chambers shelter unique bats, insects, and even entire ecosystems far from sunlight. ✨
#caves⚡#geology⚡#biodiversity
👉subscribe Interesting Planet
🌎 The world’s largest crystal cave, Cueva de los Cristales in Mexico, holds giant selenite crystals that measure up to 12 meters long. These crystals formed over 500,000 years in intense heat and humidity more than 300 meters below the surface. ✨
#minerals⚡#geology⚡#caves
👉subscribe Interesting Planet
👉more Channels
🌎 Deep inside Lechuguilla Cave in New Mexico, explorers have found rare mineral formations called "subaqueous helictites." These twisted crystals form underwater from mineral-rich drips, creating shapes never seen elsewhere. The cave stretches over 248 kilometers, making it one of the longest surveyed caves in the world. ✨
#geology⚡#caves⚡#minerals
👉subscribe Interesting Planet
👉more Channels
🌎 Deep within Mexico’s Cave of Swallows, birds plunge over 370 meters in freefall—a vertical drop so vast, entire skyscrapers could fit inside. This limestone sinkhole is among the world’s largest cave shafts, showcasing nature’s dramatic underground architecture. ✨
#geology⚡#birds⚡#caves
👉subscribe Interesting Planet
🌎 Salt crystals can form “cave chandeliers” in arid underground lakes. These sparkling formations grow when salty water evaporates, leaving dazzling, fragile mineral structures hanging from cave ceilings. ✨
#geology⚡#caves⚡#minerals
👉subscribe Interesting Planet
🌎 Hidden deep beneath the Yucatán Peninsula in Mexico, the Sistema Sac Actun is the world’s longest underwater cave system. Stretching over 370 kilometers, these flooded limestone tunnels were formed by rainwater dissolving rock over thousands of years. Archaeologists have found ancient human and animal fossils preserved in the caves, including remains over 13,000 years old. ✨
#caves⚡#archaeology⚡#fossils
👉subscribe Interesting Planet
👉more Channels
🌎 Deep inside Mexico’s Naica Mine, giant crystals of gypsum grow in the Cave of the Crystals, reaching up to 11 meters long. The cave’s extreme heat—up to 58°C—and high humidity make exploration challenging, and the crystals formed over at least 500,000 years in mineral-rich underground water. ✨
#caves⚡#crystals⚡#geology
👉subscribe Interesting Planet
🌍 Slovenia’s Škocjan Caves feature an underground canyon over 100 meters deep—the largest in Europe. This karst wonder drains rivers directly from the surface into vast hidden chambers. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels