Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
An #FBI Boston investigation has resulted in charges against 30 individuals for their roles in a global insider trading scheme that netted tens of millions in illicit profits.
The #FBI executed arrests in AL, CA, FL, NJ, and NY today for individuals who are accused of capitalizing on confidential information stolen from leading corporate law firms advising on mergers & acquisitions in Massachusetts and elsewhere.
Two subjects, located in Israel and Russia, are actively being sought.
1:11 PM · May 6, 2026
X LINK
Read more about today's takedown: https://ow.ly/tyCh50YVHRu
Now do CONGRESS...
Excongresista y lobista estadounidense condenado por actuar como agente no registrado de Venezuela en relación con un contrato de 50 millones de dólares.
Un jurado federal en Miami declaró culpable al excongresista estadounidense David Rivera de ejercer presión en secreto en nombre del gobierno venezolano y de lavar millones de dólares vinculados a ese trabajo, en violación de la Ley de Registro de Agentes Extranjeros.
Obtenga más información sobre la investigación realizada por #FBI y nuestros socios encargados de hacer cumplir la ley:
https://www.justice.gov/usao-sdfl/pr/former-us-congressman-and-lobbyist-convicted-acting-unregistered-agents-venezuela
Panic and protests at the #FBI😮
“According to an email from acting Director Brian Driscoll and reviewed by The Gateway Pundit, each field office is required to submit a list of all personnel, current and former, who were involved in January 6th investigations/prosecutions by noon on Tuesday, February 4th.”
Politics, retribution behind FBI purge, agents allege in new lawsuit against Patel, Bondi
Three senior FBI officials who were abruptly fired last month by Kash Patel, the FBI director, are claiming in a new lawsuit against the Trump administration that they were illegally terminated at the direction of the White House for purely political reasons.
The complaint, filed in U.S. District Court in Washington, D.C., Wednesday, alleges Patel told one of the agents that his job as FBI director depended on firing agents involved in past investigations of President Trump.
Patel allegedly said "he had to fire the people his superiors told him to fire, because his ability to keep his own job depended on the removal of the agents who worked on cases involving the President," the lawsuit alleges.
"Patel explained that there was nothing [anyone] could do to stop these or any other firings, because 'the FBI tried to put the President in jail and he hasn't forgotten it,'" the complaint claims. According to the complaint, former FBI agent Brian Driscoll indicated he believed Patel was referring to his superiors at the White House and the Justice Department which "Patel did not deny."
#Trump#FBI
👂More on Trump's Ear ⚠️
🔍🏛️EXCLUSIVE: FBI DIVERTS 25% OF AGENTS TO IMMIGRATION — CHILD CRIMES LEFT UNDERSTAFFED
🔹 Over six thousand FBI agents (quarter of all staff) reassigned to immigration cases in Trump's first 9 months 👮
🔹 Massive 23X increase from previous levels — agents pulled from child exploitation, terrorism, corporate fraud 🚨
🔹 ICE death toll hits 18 in 2026 as Cuban immigrant dies in Georgia detention — suspected suicide 💀
🔹 Federal charges filed against Salvadoran man shot by ICE in California traffic stop gone wrong 🚔
When immigration becomes top priority, who's protecting kids from predators? Priorities matter 🔥⚖️
#Immigration#FBI
@america