Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
From #AS_Archive
Op-ed: Human Rights Under Siege: How security forces in #Oromia fuel terror and fear to control residents through lawlessness
Many have been shocked by reports of the wanton violence gripping #Ambo in West Shewa zone of Oromia, detailed in recent news coverage, including by Addis Standard, and a wave of social media posts over the past three days describing fear, abuse, and alleged attacks by a group known as “120.”
Yet these revelations are less surprising than they are confirming, pointing to a deeper breakdown of law and order in the region.
In January 2025, Addis Standard warned of the long-term risks posed by the expansion of irregular security structures and coercive enforcement practices across parts of Oromia.
Accounts now emerging from Ambo, of harassment, extortion, and unchecked violence, echo those earlier concerns about the human cost of a security approach increasingly described by residents as rule by fear.
Revisit the full version the 2025 op-ed in our archive for deeper context and analysis.
https://addisstandard.com/human-rights-under-siege-how-security-forces-in-oromia-fuel-terror-fear-to-control-residents-through-lawlessness/
#Ethiopia: Residents of #Ambo recount a city ‘under siege’ by ‘criminal gangs’ after social media revelations expose disturbing abuses
Residents of Ambo city, in west #Shewa zone of #Oromia regional state, say they are “living in fear” amid “a pattern of violence, intimidation, and impunity.”
Many are speaking up following a wave of social media posts over the past two days that have brought renewed scrutiny to rampant abuses in the city of civilians by organized group of men called “120”.
Multiple videos and pictures, shared widely on social media networks and echoed in messages sent to Addis Standard, describe incidents ranging from public beatings and arbitrary detention to extortion and, in some cases, killings.
While Addis Standard did not independently verify these videos and pictures, residents who reached out pleasing to share their accounts speak of a harrowing experience over the past “two years.”
“We are living in a city under siege,”
Read more: https://addisstandard.com/?p=56525
News: Fuel shortages deepen in #Addis_Abeba, regional cities as drivers endure prolonged queues
Drivers in Addis Abeba and several regional cities report worsening fuel shortages, with prolonged queues and dwindling supplies deepening the strain caused by recent price hikes.
At present, beyond rising costs, fuel is reportedly becoming increasingly scarce in cities including #Mekelle, #Jimma, #Ambo and #Bahir_Dar. Drivers who spoke to Addis Standard described spending hours in queues at fuel stations, often with no guarantee of securing supply.
A public transport driver in Mekelle said the situation has deteriorated sharply. “Beyond the price hike, it feels like fuel is heading toward complete disappearance. We are buying a 20-litre jerrycan for 8,000 birr, and that too after waiting in line for more than five hours,” he said.
Read more: https://addisstandard.com/?p=55586
News: EPRP calls for nationwide protest on May 8 amid concerns over electoral conditions
The Ethiopian People’s Revolutionary Party (#EPRP) has called for a nationwide peaceful protest to be held on May 8, 2026, citing what it described as the absence of “enabling conditions” for a credible election in #Ethiopia.
In a statement sent to Addis Standard today, the party said the planned demonstrations will take place in several major cities, including #Addis_Abeba, #Mekelle, #Bahir_Dar, #Gondar, #Hawassa, #Adama, and #Ambo, urging #Ethiopians to join what it described as a peaceful effort to demand political reforms.
The EPRP said it supports the transfer of power through elections but argued that current conditions do not allow for a “free, fair, and credible” vote. It accused the ruling Prosperity Party of attempting to conduct what it termed a “pseudo-election” aimed at extending its hold on power, describing the process as
Read more: https://addisstandard.com/?p=56410
Area Sales Manager
#ethiochicken_ethiopia
#business
#Bule | #Ambo | #Gambela | #Ginir | #Hosaena | #Yirgachefe | #Sheno
BSc Degree in Animal Science, Veterinary field of study
Duties & Responsibilities:
- Develop specific plans to ensure sales growth agent appointment in the territory
- Map how to achieve sales volume through prioritizing to make big achievement with minimum effort and shorter time
Quanitity Required: 20
Minimum Years Of Experience: #0_years
Deadline: December 16, 2023
How To Apply: Submit your applications (Cover Letter) including a detailed CV via email: [email protected]
N.B: Please title your application with the subject line: - " Area Sales Manager" and Specify the area you are applying for
#In_Depth_Analysis: The #Hormuz Entanglement: Why #Ethiopia’s fuel crisis is a perfect storm of #war, #graft, and #reform
While the immediate catalyst appears to be the high-stakes military escalation between the U.S., Israel, and Iran, a deeper look reveals that Ethiopia’s fuel misery is a complex entanglement. It is a “perfect storm” where geopolitical vulnerability, a domestic system rotting from within, and a painful macroeconomic experiment have collided to leave 120 million people running on empty.
Until the govt can clean its own house, root out the “senior decision-makers” profiting from the black market, and navigate the treacherous waters of Middle Eastern diplomacy, the accounts emerging from #Gonder to #Jimma to #Ambo, and from #Hawassa to #Bishoftu and #Mekelle, point to an Ethiopia that will remain running on empty.
It will be a country “stalled at the intersection of a distant war it cannot control and a local crisis of governance it has yet to master”...
https://addisstandard.com/?p=56099