Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace