Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
News: #Djibouti President Ismaïl Omar Guelleh re-elected for sixth term after victory in latest vote
Djibouti's President Ismail Omar #Guelleh on Saturday claimed a landslide victory in an election that secured his sixth straight term at the helm of the strategically placed Horn of Africa nation.
Guelleh won Friday's presidential election with 97.8 percent of the vote, according to official results. He beat his sole opponent Mohamed Farah Samatar, little known by the general public, who secured just 2.2 percent of the vote, according to interior ministry figures.
"Re-elected", the 78-year-old declared in a social media post ahead of the official results, after early results gave him a huge lead. Guelleh has ruled the tiny nation of one million people for 27 years with an iron grip. He has made his name leveraging Djibouti's key location to turn it into an international military .......
https://www.facebook.com/AddisstandardEng/posts/pfbid02cuqZZnyp5EcLHnw4yaoE6G6tQWm3xJDZVgu5ERGMHCrJDoKr8gDmbM5xPnAebEG4l
News: #PM_Abiy visits #Djibouti, tours Doraleh Port weeks after #Egypt signs port and energy deals
Prime Minister Abiy Ahmed arrived in Djibouti today for talks with President Ismaïl Omar #Guelleh and a tour of the Port of #Doraleh, weeks after Egypt signed cooperation agreements with Djibouti on port development, logistics, and renewable energy.
In a statement shared following his arrival, Abiy said discussions with President Guelleh focused on “geopolitical dynamics, regional peace and security, and strengthening bilateral cooperation,” particularly in trade, logistics, and development, reaffirming a shared commitment to stability, economic integration, and mutual prosperity.
The Prime Minister also toured the Doraleh port complex, Ethiopia’s principal maritime gateway.
The visit comes amid heightened regional attention to Red Sea logistics. On 27 December, 2025, Egypt and Djibouti signed three cooperation agreements during an official visit by Kamel....
Read more: https://addisstandard.com/?p=54486
News: Leaders of #Djibouti, #Ethiopia, #Somalia hold tripartite talks on regional peace, security
Ismaïl Omar #Guelleh hosted a tripartite meeting with #Abiy_Ahmed Ali and #Hassan_Sheikh Mohamud in Djibouti on Wednesday, with discussions focusing on peace and security in the Horn of Africa and broader regional cooperation.
According to a statement from the Djiboutian presidency, the leaders met at the private residence of President Guelleh in Haramous during an Iftar dinner, where they held consultations aimed at strengthening coordination and collective responses to shared regional challenges.
The discussions covered peace and security in the region, the progress of economic integration among countries in the subregion, and issues of common interest affecting the three nations. The leaders also exchanged views on the prevailing political and security situation in the Horn of Africa.
The meeting further addressed the ongoing conflict in the Middle East .....
Read more: https://addisstandard.com/?p=55774
Four children killed in #Djibouti 'drone strike' explosion: official, NGO
Four children were killed in southern Djibouti in an explosion, authorities said late Tuesday, with a human rights group saying it was a drone strike.
The children died in an explosion in the #Dhikil region in #Afar, public prosecutor Hassan Mohamed Hassan said in a statement, calling it a tragic event.
Afar's community feels marginalised by President Ismail Omar #Guelleh, a member of the majority Issa community, who has ruled the country with an iron fist since 1999.
"Two children, aged six and seven (a girl and a boy), were killed at the scene, and on Tuesday two others succumbed to their injuries due to a lack of evacuation and medical care," the Djiboutian League for Human Rights (#LDDH) said in a press release.
The LDDH said the children were tending livestock when the incident took place and that....
https://web.facebook.com/AddisstandardEng/posts/pfbid037tZUcL1PYTnwEdFMBf2aLFw9oqiCJtFEgDvXKgddZQQa2CBTDdSTm1p2pcNcTkj9l
#Djibouti leader wary of #Israel’s presence in #Somaliland
Djibouti President Ismail Omar #Guelleh on Friday warned that the establishment of an Israeli military base in the strategic port city of #Berbera in Somaliland will pose a direct threat to regional stability.
Speaking to a local media, Guelleh accused Israel of exploiting Somaliland’s decades-long quest for statehood to secure a foothold in the Horn of Africa.
He expressed deep concern that the authorities in #Hargeisa might agree to any geopolitical concession in exchange for formal recognition.
The veteran leader also leveled uncharacteristically blunt criticism at the United Arab Emirates, describing the Gulf nation as Israel’s primary “gateway” into the region.
Guelleh pointed out that the #UAE is driving strategic shifts in the Horn of Africa and the #Red_Sea that exacerbate existing conflicts. He further alleged....
https://web.facebook.com/AddisstandardEng/posts/pfbid02eCjUg8BmbcGMNdTaybhh1dcaRUKUG8Gt8batRZvmsGemat4LxFLfoWLCD8eVbcdUl