Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#IGAD welcomes #Sudan’s return to regional bloc after two-year suspension
The Intergovernmental Authority on Development (IGAD) has welcomed Sudan’s decision to resume full participation in the regional organization, describing the move as a step toward strengthening regional unity and cooperation.
In a statement issued today, IGAD said Sudan’s return reaffirms the bloc’s commitment to peace, stability, and collective action across the Horn of Africa and neighboring regions.
Sudan suspended its participation in IGAD in mid-January 2024, objecting to the bloc’s handling of its internal conflict.
https://addisstandard.com/?p=55103
IGAD Responds To Eritrea’s Withdrawal, Allegations Of “Forfeited” Mandate. Read more.
https://borkena.com/2025/12/14/eritrea-igad-responds-to-eritreas-withdrawal-allegations-of-forfeited-mandate/#Eritrea#News#IGAD
Eritrea’s Exit from IGAD: A Regime’s Political Maneuver, Not the Voice of Its People. Read more.
https://borkena.com/2025/12/12/eritreas-exit-from-igad-a-regimes-political-maneuver-not-the-voice-of-its-people/#Eritrea#IGAD#HornofAfrica
#Ethiopia: Weeks after a disputed peace deal, #Amhara Regional Government says AFAHD vice chair Colonel Fentaw Muhaba joins peace process
Weeks after a disputed peace agreement between the Amhara Regional Government and the Amhara #Fano People’s Organization (#AFAHD), the regional government announced that Colonel Fentaw Muhaba, Vice Chair and Military Commander-in-Chief of AFAHD, has entered the peace process along with his forces.
In a statement, the regional government said Colonel Fentaw, who also commands AFAHD’s Wollo Province forces, accepted the peace alternative as part of the agreement reached through negotiations mediated by the African Union (#AU) & the Intergovernmental Authority on Development (#IGAD). Officials described his move as a step toward de-escalation and stabilizing the region.
The announcement follows a controversial “peace agreement” reported on 4 December 2025, in which state media said the Amhara Regional Government had signed ....
Read more: https://addisstandard.com/?p=54501
#Sudan’s Democratic Bloc split over unauthorized talks in #Ethiopia
Public divisions emerged within Sudan’s Freedom and Change – Democratic Bloc on Sunday after member organizations held unauthorized meetings with international mediators in the Ethiopian capital, #Addis_Abeba.
The “Quintuple Mechanism”—comprising the #African_Union, #IGAD, the #United_Nations, the #Arab_League, and the #European_Union—is seeking to bridge the gap between Sudanese political forces to launch a process on the country’s future governance.
Democratic Bloc spokesperson Juma al-Wakil disavowed the delegation in Addis Ababa, stating the coalition “did not participate in the meeting and did not send a representative delegation.” He added that no authorization had been issued for any entity to represent the bloc in the consultations.
Al-Wakil, who is affiliated with Minni Minawi’s Sudan Liberation Movement (#SLM), said that if members participated, they did so in a “personal or ....
https://sudantribune.com/article/310749
#IGAD envoy: #Sudan crisis internationalized; Berlin conference to mobilize aid and de-escalate
The five-member mechanism overseeing the civilian track of the #Berlin conference stated on Sunday that the Sudanese crisis has transcended its borders and become internationalized, affecting the global community, particularly regarding international humanitarian law.
The quintet—comprising the #African_Union, #United_Nations, #European_Union, #Arab_League, and the Intergovernmental Authority on Development (IGAD)—is working to find a resolution to the ongoing conflict between the Sudanese army and the Rapid Support Forces (#RSF).
IGAD Envoy for Sudan Lawrence Korbandy told Sudan Tribune that the Berlin conference is taking place as the international community is preoccupied with tensions in the #Gulf, #Iran, and #Israel.
This has marginalized the Sudan crisis despite it being the..........
https://www.facebook.com/AddisstandardEng/posts/pfbid02sejfuDbzhzZTvFL5DtZY48Gx561Xnzs2h5uYDBosFYGn16WjUGzPKn9ugZMvjkGvl
#Sudan slams #Uganda for hosting paramilitary chief
Sudan's army-aligned government on Sunday criticised #Kampala for hosting rival paramilitary chief Mohamed Hamdan Daglo, slamming his reception by Uganda's president as an "affront to humanity".
#Hemeti on Friday met with Ugandan President Yoweri #Museveni at #Entebbe's State House, a day after a United Nations probe found his forces had committed acts of genocide in #Darfur.
Sudan's foreign ministry on Sunday criticised the meeting, saying the #RSF's atrocities had been "documented by the international community and condemned by regional organisations of which Uganda is a member", including the African Union & the Intergovernmental Authority on Development (#IGAD).
Daglo, speaking during his visit, said he travelled to Uganda after President Museveni was approached by the Sudanese army seeking his mediation.
His visit came a week ...
https://web.facebook.com/AddisstandardEng/posts/pfbid0RVfv7fGAkLcW1TgpDMTNhYyCwS2wG1KVnGgVMpCy7DS1XtYtuU8nnEyrcYCRtLaal