Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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: #Southwest State president resigns after federal forces seize #Baidoa
Somalia’s Southwest State President, Abdiaziz Hassan Mohamed Laftagareen announced his resignation on Monday, hours after federal troops and allied armed groups entered Baidoa following clashes that left at least two people dead and 25 others wounded.
In a brief statement posted on his official Facebook page, Laftagareen said the resignation was effective immediately, without providing further details.
His whereabouts remain unclear.
Earlier in the day, forces of the Somali National Armed Forces, backed by allied militias, moved into Baidoa and reportedly took control of key installations, including the police station and major business centers, encountering limited resistance.
Regional forces loyal to Laftagareen were said to have withdrawn from parts of the city.
According to local reports, strategic sites including the airport and the.......
https://x.com/addisstandard/status/2038849050108416203?s=20
🤩FAA расследует опасное сближение двух Boeing в Нэшвилле
📌Федеральное авиационное управление США начало расследование после инцидента в зоне аэропорта Нэшвилла. Два рейса Southwest Airlines оказались на минимальной дистанции – вертикальный интервал между самолётами составил около 500 футов (152 метра)
🔵Рейс 507 выполнял заход на посадку в порывистый ветер и ушёл на второй круг. При наборе высоты самолёт оказался на курсе, пересекающемся с рейсом 1152, который взлетал с параллельной полосы. По данным экспертов, сработало бортовое предупреждение о возможном столкновении, после чего экипажи выполнили манёвры уклонения
🔵Оба рейса завершились благополучно: 507 позже приземлился, 1152 продолжил взлёт. Southwest отметила профессионализм пилотов
⬅️Подобные ситуации – напоминание о том, насколько важна слаженная работа экипажа и диспетчеров
Лёгкое небо
#aviation#news#FAA#Southwest
#Somalia: Federal government declares mandate of #Southwest state president expired
Somalia's federal government escalated a deepening political standoff with the #Southwest_State administration on Sunday, declaring the regional leadership's term in office officially expired and moving to initiate a transition process.
In a formal statement, the Federal Ministry of Interior, Federal Affairs and Reconciliation asserted that President Abdiaziz Hassan Mohamed, popularly known as Laftagareen, no longer holds a valid mandate.
The ministry stated it has been tasked with overseeing the selection of new leadership to prevent a power vacuum in Somalia.
The move marks a significant fracture in the delicate relationship between Mogadishu and the federal member states.
Federal officials argued that the move is a necessary step to uphold constitutional timelines, while supporters of......
https://www.garoweonline.com/en/news/somalia/somalia-federal-government-declares-mandate-of-southwest-state-president-expired
News: #AU chairperson urges dialogue, restraint amid rising tensions in #Somalia’s Southwest State
The African Union Commission (#AUC) Chairperson, Mahmoud Ali Youssouf, has called for dialogue and restraint among Somali stakeholders amid rising tensions in the #Southwest State of Somalia.
In a statement released by the AUC, the Chairperson said he is closely monitoring developments in the region and expressed concern over escalating tensions and their potential impact on the country’s stability, security, unity, and humanitarian situation.
He underscored the importance of the National Consultative Council as a key platform for inclusive dialogue and consensus-building, urging all parties to make constructive use of it to resolve differences peacefully.
The statement emphasized that disputes between the Federal Government and Federal Member States should be .......
https://www.facebook.com/AddisstandardEng/posts/pfbid0s5reSjXyuiniXuYjiot3AckwjHmjs6TqtDhGeL7NJRV3Bat3MHkJ8sXogGJrSzDql
#Somalia: #Southwest President Laftagareen resigns from Hassan Sheikh Mohamud's JSP Party
Southwest State President Abdiaziz Hassan Mohamed Laftagareen has resigned from the Justice and Solidarity Party (#JSP), led by #Somali President Hassan Sheikh Mohamud, in the latest sign of escalating tensions between his administration and the federal government.
Laftagareen, who had been serving as deputy chairman of the JSP, announced his resignation on March 18, 2026.
“I, President of Southwest State H.E. Abdiaziz Laftagareen, resign as Deputy Chairman of the JSP effective today, March 18, 2026. I cannot support unconstitutional actions that weaken our unity. My commitment remains to Somalia’s unity, democracy and the rule of law,” he said in a statement.
The regional leader argued that Somalia’s only legitimate constitutional framework remains the 2012 provisional constitution,....
https://www.hiiraan.com/news4/2026/Mar/204696/southwest_president_laftagareen_resigns_from_hassan_sheikh_mohamuds_jsp_party.aspx
Federal government suspends #Mogadishu–#Baidoa flights after Southwest halts cooperation
#Somalia’s federal government on Tuesday suspended civilian flights between Mogadishu and Baidoa, in a move widely seen as increasing pressure on #Southwest State authorities amid a deepening political standoff.
Local sources said that as of Tuesday morning, commercial passenger aircrafts were unable to land in Baidoa following the decision. Only #United_Nations and cargo flights were being permitted to operate during the suspension.
Officials in Southwest State condemned the measure.
“The Somali government has stopped passenger planes from arriving in Baidoa. People entered the airport at 6:00 this morning, and they have not been allowed to departure yet,” said Ilyas Ali Nur, a senior official in the regional administration.
Sources indicated that flight clearances had been.....
https://www.hiiraan.com/news4/2026/Mar/204688/federal_government_suspends_mogadishubaidoa_flights_after_southwest_halts_cooperation.aspx