Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🎙President Vladimir Putin's statement at the state awards ceremony for Russian athletes(Moscow, April 22, 2026)
💬 I am sincerely pleased to congratulate everyone on your successes. Your performances and results are a substantial contribution to reaffirming Russia’s leading position in world sport – a strong and unshakable position, despite all the underhanded attempts to weaken it.
☝️The disgraceful – and, I would say, cowardly – politically motivated conduct of the previous leadership of the International Olympic Committee inflicted enormous damage on the Olympic movement and on the very principles of Olympism.
Selective sanctions against Russian athletes, imposed under the pretext of condemning Russia’s actions to defend our people and our interests in the context of the conflict in Ukraine, while ignoring numerous other similar tragedies and armed conflicts around the world, merely exposed the corruption and political bias of a significant part of the international sporting establishment.
👉I hope that the new leadership of the International Olympic Committee and other international sports organisations will overcome this legacy as soon as possible – a heavy and shameful legacy left by their predecessors.
I am certain that many more sporting triumphs lie ahead for you, as well as for your teammates representing a wide range of disciplines – including at the biggest international competitions – and, without fail, under our national flag and to the sound of Russia’s national anthem.
Russia is steadily returning to the world’s sporting arenas, and doing so with dignity. Last season, our swimmers, fencers, canoeists, gymnasts, judokas and wrestlers all delivered brilliant victories.
The truly special – indeed unique, without any exaggeration – achievement was the triumph of Russia’s Paralympians in Milan. As you know, they secured third place in the overall standings with a team that was several times smaller than those of their main rivals. This was an outstanding result. These victories were won not by numbers, but by skill, talent and the will to win.
Russia will continue to develop sport in all areas, ensuring the broadest possible opportunities for participation in elite sport, professional sport and mass sport alike, while actively promoting sport above all among children and young people. Because, as we all know well, sport is not simply about physical strength and agility – it is a way of life built on the values of health, mutual respect, and, crucially, determination and responsibility.
Read in full
#TeamRussia
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russisches Paralympisches Komitee:
#TeamRussia belegt den DRITTEN PLATZ im Medaillenspiegel bei den Paralympischen Spielen 2026!
Trotz eines Teams von nur sechs Athleten und einem Guide lieferten unsere Paralympioniken eine phänomenale Leistung ab.
12 MEDAILLEN:
🥇 8 Gold
🥈 1 Silber
🥉 3 Bronze
Im Gesamtklassement belegte Russland Platz 3 – hinter China und den USA, die beide mit deutlich größeren Teams angetreten sind.
💬 Der Präsident des Russischen Paralympischen Komitees, Pavel Rozhkov, erklärte:
Die Ergebnisse haben alle Erwartungen übertroffen! Auch mit einem kleinen Team hat Russland ein starkes Zeichen gesetzt und eine triumphale Rückkehr auf die internationale Sportbühne gefeiert.
👏 Herzlichen Glückwunsch und größten Respekt an unsere herausragenden Athleten: Anastasia Bagijan und ihren Begleiter Sergej Sinyakin, Warwara Worontschichina, Iwan Golubkow, Alexej Bugajew, Dmitrii Fadejew und Monzer Philippe Shebbo.
@RusBotschaft
#Russland#Sport
Прорыв 2021 года 🐻🔥
Даниил Медведев, вторая ракетка мира, показал феноменальный результат в уходящем 2021 году⚡Даниил завоевал свои чемпионские титулы на турнирах:
🔹Open 13 Provence в Марселе (8-14 марта)
🔹Mallorca Championships на Майорке (20-26 июня)
🔹National Bank Open Presented by Rogers в Торонто (9-15 августа )
🔹US OPEN ITF Grand Slam в Нью-Йорке (30 августа-12 сентября)
Даниил также завоевал несколько командных титулов, о которых мы расскажем уже в следующих постах🤫
Поздравляем с незабываемым сезоном и желаем самых ярких побед и достижений в 2022 году🏆🔥
#формулатх#теннис#tennis#formulatx#atp#teamrussia
Аслан Карацев остается в ТОП-20 мирового рейтинга после окончания сезона💪😄
Аслан показал отличный результат в 2021 году, завоевав титулы на турнирах:
- ATP Qatar ExxonMobil Open (8-14 марта)
- ATP Kremlin Cup (16-24 октября)
- ATP Dubai Duty Free Tennis (2-6 ноября)
Аслан провёл великолепный сезон🤩
Желаем в 2022 году получить еще больше титулов и одержать еще больше побед🏆
#tennis#formulatx#формулатх#теннис#atp#wta#teamrussia
🇷🇺🤘🏼Андрей Рублёв стал победителем турнира ATP-250 в Марселе в одиночном и парном разряде 💪🏻
👏🏻Первый титул в начале сезона🔝 Поздравляем и желаем продолжать завоевывать титулы❗
#formulatx#andreyrublev#формулатх#андрейрублёв#teamrussia
🚨В завершении рубрики “Итоги года для российского тенниса 2021”, вспоминаем о замечательных результатах наших спортсменов на Олимпийских играх в Токио‼️
🔹Карен Хачанов серебро финал одиночного разряда
🔹Анастасия Павлюченкова и Андрей Рублёв взяли золото в финале парного разряда
🔹Елена Веснина и Аслан Карацев взяли серебро в финале парного разряда
🙏Благодарим всех спортсменов с невероятно насыщенным победами год! Мы верим в вас и гордимся вами❤️ Это было очень мощно👍
#tennis#formulatx#формулатх#теннис#throwbackthursday#atp#wta#teamrussia