Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
"El Comando #África de los #EstadosUnidos (#AFRICOM) confirmó que llevó a cabo un ataque aéreo contra las fuerzas de Al-Shabaab el pasado 15 de febrero cerca de Gelib, en la región de Middle Juba en #Somalia, donde se presumía que estaban secuestrados los médicos cubanos Assel Herrera y Landy Rodríguez."
News: Deputy #US Secretary of State to visit #Ethiopia, meet PM Abiy, #AU chair
US Deputy Secretary of State Christopher Landau is set to visit Ethiopia as part of a regional tour that will take him to #Egypt, #Kenya, and #Djibouti between January 24 and February 1, the US Department of State announced.
According to a statement issued by the Office of the Spokesperson, Landau will travel to Ethiopia alongside the Commander of US Africa Command (#AFRICOM), General Dagvin Anderson. During his visit to Addis Abeba, Landau is expected to promote opportunities for US commercial engagement with the Ethiopian government and the private sector.
The statement said the Deputy Secretary will also hold discussions with Ethiopian officials, including Prime Minister Abiy Ahmed, focusing on regional peace and security issues.
In addition, he will meet with AU Commission Chair Mahmoud Ali...
https://web.facebook.com/AddisstandardEng/posts/pfbid02NWzYTrBPpfi2CeqeE5sHCrXFz3UCj3kbNkHU7DBrk9396y48rFcgPGFrdrK2Yjoil
News: #PM_Abiy receives #US Deputy Secretary Christopher Landau, AFRICOM commander as #Ethiopia, US agree to deepen security cooperation
Prime Minister Abiy Ahmed said he received a courtesy visit from US Deputy Secretary of State Christopher T. Landau and the Commander of the United States Africa Command (#AFRICOM), General Dagvin Anderson, describing the engagement as warm and constructive and underscoring the importance of continued collaboration and mutual respect between the two countries.
The visit comes as part of a regional tour by Deputy Secretary Landau that includes #Egypt, #Ethiopia, #Kenya, and #Djibouti, scheduled to run from 24 January to 1 February.
Earlier, Foreign Minister Gedion Timothewos held talks with Landau in Addis Abeba, with discussions focusing on strengthening bilateral relations and exchanging views on regional issues of mutual interest.
During their stay, Landau and General Anderson also visited the International Aviation ....
Read more: https://addisstandard.com/?p=54807
News: #US Assistant Secretary Christopher Landau, AFRICOM commander arrive in #Ethiopia, visit Air Force aviation expo
U.S. Assistant Secretary of State Christopher Landau arrived in Ethiopia today as part of a regional tour that includes #Egypt, Ethiopia, #Kenya, and #Djibouti, scheduled to run from 24 January to 1 February.
The Commander of the U.S. Africa Command (#AFRICOM), General Dagvin Anderson, is also in Ethiopia as part of the visit.
Today, Landau and General Anderson visited the International Aviation Expo organized by the Ethiopian Air Force, according to the Ethiopian National Defense Force (#ENDF). Field Marshal Birhanu Jula, Chief of General Staff of the Ethiopian National Defense Force, also took part in the visit.
The expo showcased aircraft, defense technologies, and related products from the Ethiopian Air Force, the Defense Engineering Industry Group,..
https://www.facebook.com/AddisstandardEng/posts/pfbid021qedgKswfSFzdABsQXmFSvjuiRtWQedXpLYXJysCdk1MBnWvdx4JZJTmEng9jPGRl
#US Forces conduct strike targeting ISIS-Somalia
In coordination with the Federal Government of Somalia, U.S. Africa Command (#AFRICOM) conducted an airstrike targeting #ISIS-#Somalia on March 16, 2026.
The airstrike occurred in the vicinity of the Golis Mountains, approximately 45 km southeast of #Bossaso.
AFRICOM, alongside the Federal Government of Somalia and Somali Armed Forces, continues to take action to degrade ISIS-Somalia’s ability to threaten the U.S. Homeland, our forces, and our citizens abroad.
Specific details about units and assets will not be released to ensure continued operations security. (Source: AFRICOM)
News: #AFRICOM signals deeper #US security, economic engagement in #East_Africa
The Commander of the United States Africa Command (AFRICOM), General Dagvin R.M. Anderson said Washington is seeking to more closely align security cooperation with economic investment across #Africa, citing recent engagements in #Ethiopia, #Kenya, and #Djibouti as part of a broader strategy to address growing security threats while fostering stability and development.
Speaking during a digital press briefing yesterday, General Anderson said he recently concluded a joint visit to East Africa with US Deputy Secretary of State Christopher Landau, where discussions focused on counterterrorism, regional security, and the link between stability and economic growth.
In Ethiopia, Anderson said he attended the Black Lion Air Show marking the 90th anniversary of the Ethiopian Air Force, underscoring what he described as the long-standing US–Ethiopia security partnership....
Read more: https://addisstandard.com/?p=54989
#US shifts Al-Shabaab combat operations from #Djibouti to #Kenya?
The United States and Kenya have launched a $71 million initiative to upgrade the airfield at #Manda Bay, a facility situated directly adjacent to the #Somali border.
While the project focuses on infrastructure in Kenya, analysts view the move as part of a major strategic realignment by US Africa Command (#AFRICOM) to encircle Al-Shabaab threats originating from Somalia, while simultaneously reducing reliance on Djibouti.
Countering Threats from Somalia
The expansion involves extending the runway to 10,000 feet, allowing the base to support large cargo and military aircraft. This capability is designed to boost refueling options and rapid security responses for operations targeting militants in the Horn of Africa.
General Dagvin R.M. Anderson of AFRICOM noted that the project strengthens the security alliance against regional threats....
https://www.ftlsomalia.com/us-shifts-al-shabaab-combat-operations-from-djibouti-to-kenya-somaliland/