Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 Astronomers have detected rapid radio bursts—millisecond-long signals from distant space. These intense pulses hint at extreme events, like collapsing stars or magnetars, yet their exact origin remains one of space’s most intriguing mysteries. ✨
#astronomy⚡#space⚡#mysteries
👉subscribe Interesting Planet
🌎 Space isn’t silent—astronomers have recorded eerie “whistles” and “choruses” from planets like Jupiter. These radio waves, caused by charged particles moving through magnetic fields, are transformed into sound waves we can hear when played back on Earth. The haunting tunes of space reveal hidden cosmic activity all around us. ✨
#astronomy⚡#space⚡#mysteries
👉subscribe Interesting Planet
🌎 Off the coast of Scotland, the Orkney Islands’ Tomb of the Eagles is a Stone Age burial site containing over 16,000 human and animal bones. Archaeologists discovered that the tomb, built around 3150 BCE, was used for more than 800 years before being sealed. ✨
#archaeology⚡#mysteries⚡#prehistory
👉subscribe Interesting Planet
🌎 The "Bloop" is one of the loudest underwater sounds ever recorded. Detected by NOAA hydrophones in 1997, this low-frequency noise was picked up over 5,000 kilometers apart. Scientists later identified melting icebergs as the likely source, not a sea creature or submarine volcano. ✨
#ocean⚡#sound⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 Mysterious low-frequency sounds known as "The Upsweep" have been picked up by underwater microphones in the Pacific Ocean since 1991. This persistent sound rises and falls in pitch, lasts several seconds, and is strongest in spring and autumn. Its source remains unidentified, but some researchers suggest volcanic activity near the origin point may be involved. ✨
#ocean⚡#mysteries⚡#sound
👉subscribe Interesting Planet
👉more Channels
🌎 On the border between Egypt and Sudan lies Bir Tawil, a peculiar territory claimed by neither country. Due to a mapping oddity, Bir Tawil is one of the world’s rare “unclaimed” lands, standing as a real-life no man’s land on modern maps. ✨
#geography⚡#borders⚡#mysteries
👉subscribe Interesting Planet
🌎 The Brandberg Mountain in Namibia is famous for its mysterious White Lady rock painting, estimated to be at least 2,000 years old. Archaeologists debate whether the figure represents a woman, man, or ritual dancer, and the exact meaning of the painting remains unclear. The site contains over 45,000 individual rock paintings. ✨
#archaeology⚡#Namibia⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 The underwater Stone Circles of Lake Michigan were discovered in 2007 by archaeologists using sonar. The stones are arranged in a circle about 12 meters below the surface. One stone features a carving resembling a mastodon, hinting at a possible age of over 10,000 years. ✨
#mysteries⚡#archaeology⚡#lake
👉subscribe Interesting Planet
👉more Channels
🌎 Bolshoi Zayatsky Island in Russia’s White Sea features hundreds of mysterious stone labyrinths, or “Babylons,” built by unknown people. Most date back 2,000–3,000 years. Archaeologists suggest they served ritual or astronomical purposes, but their exact function remains unproven. ✨
#mysteries⚡#archaeology⚡#Russia
👉subscribe Interesting Planet
👉more Channels
🌎 The ancient city of Hattusa, capital of the Hittite Empire, features massive stone walls, elaborate gates, and mysterious underground tunnels. Archaeologists found cuneiform tablets here describing treaties, religions, and daily life. The site was abandoned around 1200 BCE for unknown reasons. ✨
#Hittite⚡#archaeology⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 The disappearance of 20,000-year-old giant cave art in Chauvet Cave, France, puzzles scientists. Some images faded, while others vanished completely, possibly due to natural mineral changes, humidity, or hidden collapses in the limestone walls. The cave holds more than 1,000 preserved prehistoric paintings and engravings. ✨
#archaeology⚡#mysteries⚡#art
👉subscribe Interesting Planet
👉more Channels
🌎 Deep in the Ural Mountains of Russia, the remote plateau called Manpupuner features seven enormous stone pillars, each up to 42 meters tall. These ancient rock formations, shaped by frost and wind over millions of years, were considered sacred by Indigenous Mansi people. The pillars’ unique shapes and mysterious origin make them one of Russia’s least accessible and most enigmatic natural monuments. ✨
#geology⚡#mysteries⚡#Russia
👉subscribe Interesting Planet