Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#Somalia, #EU strengthen military cooperation in meeting between defence officials
The Minister of Defence of the Federal Government of Somalia, Ahmed Moallim Fiqi, accompanied by the Chief of the Somali National Army, General Odowaa Yusuf Rageh, today held a meeting with the Chair of the European Union Military Committee, General Seán Clancy, who is visiting Somalia.
The meeting focused on commending and strengthening military cooperation between Somalia and the European Union, particularly in the areas of troop training, the continuation of various forms of support, and the enhancement of national defence capabilities and #AUSSOM.
The meeting was attended by the European Union Ambassador to Somalia, Ms Francesca Di Mauro, along with other senior officials from both sides.
https://sonna.so/en/somalia-eu-strengthen-military-cooperation-in-meeting-between-defence-officials/
#Uganda announces plans to withdraw troops from #Somalia after 19 years
Uganda has announced plans to withdraw its troops from Somalia after nearly two decades of continuous peacekeeping operations, a move that could have significant implications for regional security and the fight against the militant group #Al_Shabab.
In a brief statement posted on X on Sunday, Uganda’s Commander-in-Chief of the Armed Forces, Gen. Muhoozi Kainerugaba, said the country’s military mission in Somalia had effectively ended and that preparations were underway for a full troop withdrawal.
“After 19 years in Somalia, we intend to completely withdraw from that country very soon,” Muhoozi said, without providing further details or a timetable.
Ugandan troops make up the largest contingent within the African Union Support and Stabilization Mission in Somalia, known as #AUSSOM, and have played a central role...
https://www.hiiraan.com/news4/2026/Jan/204267/uganda_announces_plans_to_withdraw_troops_from_somalia_after_19_years.aspx
News: Amid deepening rift Southwest State accuses #Somalia’s fed. govt of diverting ‘#Egyptian weapons’ to militias
Tensions between Somalia’s federal government and the #Southwest_State have escalated after the regional parliament speaker accused #Mogadishu of diverting weapons supplied by Egypt to local militias instead of using them against al-Shabab.
In a statement posted on 21 March, Dr. Ali Said Fiqi, Speaker of the Southwest State Parliament, alleged that firearms provided by Egypt for national security purposes had been rerouted to armed groups operating in Burhakaba district.
Egypt has in recent years increased its military cooperation with Somalia, including supplying weapons and preparing troop contributions to #AUSSOM, a new African Union-led mission replacing the previous peacekeeping framework.
#Ethiopia had earlier urged the AU and the UN to ensure inclusive consultations with key stakeholders as plans advanced to deploy a new peacekeeping....
Read more: https://addisstandard.com/?p=56042
News: #Somali president witnesses #Egyptian troop deployment to AU mission in Somalia
Somali President #Hassan Sheikh Mohamud has witnessed the formation of Egyptian forces assigned to the #African_Union Support and Stabilization Mission in Somalia (#AUSSOM), according to a report by Egypt Today, citing a statement from Egypt’s military spokesman.
The formation ceremony was attended by Egypt’s Minister of Defense and Military Production Gen. Abdel Mageed Saqr, Chief of Staff Lt. Gen. Ahmed Khalifa, and senior Egyptian military commanders. The military spokesman said the visit included briefings on the preparation, equipping, and operational readiness of Egyptian troops designated for the mission.
The program also featured training exercises and a display of vehicles intended for deployment, with officials stating the forces had completed intensive professional training to ensure....
https://web.facebook.com/AddisstandardEng/posts/pfbid02D7ibS3RJJRGZzoYDziFEYk4VKn5vmQXDQVkAtLaU2C4EuxFtVrj8HUbHXYrD4eFSl