Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
💥BREAKING! Weapons meant for Ukraine USED in the devastating terrorist attack in Israel! The Biden Administration's SHOCKING REPEATED REFUSAL on arms tracking, paired with Ukraine's notorious black market, fuels a terrifying new threat for the world. We will see MUCH MORE of this, coming soon through the Southern Border near you! ⚠️🔥#UkraineArmsScandal#MiddleEastCrisis
Listen as Sayed Mohammad Maranda discusses the critical situation unfolding in Gaza and the looming threat of escalation with Iran. The stakes are higher than ever.
#MiddleEastCrisis#Iran#USA#Israel#Netanyahu#Hezbollah#War
🔺Continuation from above
@rednile12
📌 What Happened Earlier Today
Earlier on February 28, 2026, the United States and Israel launched a coordinated military offensive against multiple targets in Iran — an operation involving aerial and missile strikes planned over weeks, according to Israeli officials.
Western powers claimed the operation aimed to neutralize what they described as “existential threats” posed by Iran’s missile and nuclear programs. However, Russia and others have condemned the U.S.–Israel assault as a premeditated, unprovoked act of aggression against a sovereign state.
🔥 Iran’s Retaliatory Tactics
Iran’s response appears to reflect a strategic approach, not a spontaneous counterattack:
🔹Missile Barrages First:
Iran fired ballistic missiles at multiple targets hosting U.S. forces and allied positions across the Gulf — including Qatar, Bahrain, Kuwait, and the UAE.
🔹Drone Saturation:
Following the missile salvos, waves of Shahed-136 drones were reportedly used to strike high-value U.S. radar and defense infrastructure once expensive interceptor systems were already engaged.
🔹 This layered method has key implications:
▪️ It forces U.S. and allied defenses to expend high-cost interceptors against cheaper threats.
▪️ It exploits cost asymmetry, where low-cost drones can wear down advanced systems economically and tactically over time.
▪️ It demonstrates Iran’s ability to integrate UAVs into broader retaliation campaigns, not just standalone strikes.
🧠 Strategic Takeaways
📍Damage to Early Warning Capabilities
If U.S. AN/FPS-132 radars are seriously degraded or destroyed, it would reduce the effectiveness of missile tracking and early warning across the region, complicating air defense coordination in a rapidly evolving war environment.
📍Cost Imbalance in Modern Air Defense
Iran’s combination of missiles and inexpensive drones highlights a structural weakness in defense architectures built around costly interceptor munitions.
📍Regional Escalation Risks
Today’s retaliation underscores how quickly localized strikes can escalate into broader conflict — dragging multiple Gulf states into direct confrontation, disrupting airspace, and threatening civilian infrastructure across the region.
♦️This is no ordinary exchange of fire — it reflects a turning point in regional warfare dynamics, where retaliation, sequencing, cost imbalances, and strategic targeting have dramatic implications for how future conflicts unfold.
RedNile Media🌊🧭
📡@rednile12
Geopolitics | Multipolarity | Sovereignty | Strategic Reality
#Iran#USA#Israel#MiddleEastCrisis#GulfSecurity
🚨 BREAKING NEWS 🚨
"Al-Quds Brigade, part of the Islamic Jihad group, claims to have captured Israeli soldiers during an operation near Gaza. Hamas reports seizing 14 tanks and IDF prisoners. Israel declares a state of war, launching 'Operation Iron Swords'. Tensions escalate."
💣💥#MiddleEastCrisis#PrisonersOfWar#IsraelVsHamas
https://www.gazeta.ru/army/news/2023/10/07/21450403.shtml
Subscribe to @BadVolfNews