Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#Sweden, national parliament election:
S (S&D) is largest in all constituencies but two in Scania where SD (ECR) leads.
SD, M (EPP), KD (EPP), L (RE) are together stronger in the South.
S, C (RE), V (LEFT), MP (G/EFA) together do best in the North and the three largest cities.
➤ europeelects.eu/sweden
🇸🇪#Sweden: The Swedish Coast Guard has seized a Syrian-flagged vessel named Jin Hui, suspected of being part of Russia’s so-called "shadow fleet".
The ship was sailing in Swedish territorial waters south of Trelleborg and had appeared on multiple sanctions lists. Its destination was unclear. Authorities also suspect the vessel may have been operating under a false flag and was reportedly carrying no cargo.
(via Reuters)
#Sweden🇸🇪
The Luleo Archipelago is a group of Swedish islands in the northern part of the Bayer Belonian, located near the city of Luleo and the mouth of the Lule River.
The sea freezes in January and remains frozen until March - April. Ice roads are cleaned by the four populated islands.
📍Sweden🇸🇪
Gorgeous evening view from the Liseberg amusement park in Sweden. 🎢
Liseberg Amusement Park is also a true symbol of love, as it was built in 1923 by merchant Lamberth for his terminally ill wife Lisa. He transformed the former pastureland into a real garden with trees, flowers, and water areas. 🌳🌺😍
After Lisa's death, the park was donated by her husband to the state, and currently, it attracts about 3 million visitors per year, making it one of the most popular entertainment and leisure destinations in Europe.
#Sweden
@voyage
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard, together with the police, has boarded another vessel suspected of operating under a false flag off the coast of Trelleborg.
The oil tanker, named "Sea Owl I", is believed to be part of Russia's shadow fleet. It was reportedly sailing under an alleged false flag on its way to the port of Primorsk in Russia after departing from Santos, Brazil. Investigators were also alerted by the fact that the ship appeared unusually light and insufficiently loaded.
After the Coast Guard boarded and took control of the vessel, the captain, which is a Russian citizen, was taken in for questioning, however, he has not been arrested yet. Meanwhile, the Russian embassy in Sweden stated earlier today that it is "monitoring the situation", with Russian officials describing the boarding as an act of "piracy".
(via Göteborgs-Posten & Reuters)
🇸🇪#Sweden - 🇷🇺#Russia: Swedish special forces, along with aviation police and the coast guard, have seized a sanctioned Russian vessel which was sailing under a false flag.
The operation took place this Friday while the ship was sailing in Swedish territorial waters in the Baltic Sea near Trelleborg.
The ship was involved in the theft of grain from the territories that Russia has occupied since July 2025.
During last summer, the ship is said to have had its flag changed from a Russian flag to a Guinean flag.
(via Göteborgs-Posten)
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard has boarded the Russian vessel ADLER in the Baltic Sea and carried out inspections on the ship which was reported to regularly transport military cargo to Russian allies in Africa.
The ADLER is operated by M Leasing LLC, a logistics company under EU sanctions and linked to the Russian Ministry of Defence.
The ship was forced to anchor off the Swedish coast yesterday morning after reportedly suffering an engine failure.
According to Swedish media, the crew is cooperating with the Swedish Coast Guard during the inspection.
(via Reuters; 📹 via @wartranslated on X)