Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 The African buffalo, also known as Cape buffalo, is responsible for more deaths in Africa than most other large animals. Adult males can weigh up to 900 kilograms and have powerful horns, making them extremely dangerous when threatened. Herds can number in the hundreds and will defend injured members against predators, including humans. ✨
#wildlife⚡#mammals⚡#danger
👉subscribe Interesting Planet
👉more Channels
🌎 Mosquitoes are responsible for more human deaths than any other animal on Earth. They transmit diseases like malaria, dengue, Zika, and yellow fever, causing over 700,000 deaths each year worldwide. Some mosquito species can breed in just a bottle cap of water. ✨
#animals⚡#danger⚡#mosquitoes
👉subscribe Interesting Planet
👉more Channels
🌎 The assassin bug, found in tropical and subtropical regions, can inject a powerful enzyme that liquefies the insides of prey. Some species can also deliver painful bites to humans that may trigger allergic reactions. Assassin bugs are responsible for transmitting Chagas disease, which affects millions in Central and South America each year. ✨
#animals⚡#danger⚡#bites
👉subscribe Interesting Planet
👉more Channels
🌎 The mosquito is considered the deadliest animal on Earth, causing over 700,000 human deaths each year. Mosquitoes spread malaria, dengue, Zika, yellow fever, and other life-threatening diseases across tropical and subtropical regions, making them a major global health threat. ✨
#animals⚡#danger⚡#diseases
👉subscribe Interesting Planet
🪐 The asteroid (137108) 1999 AN10 is an Apollo-type near-Earth object roughly 800 meters wide, and its orbit brings it close enough to Earth every few decades that scientists label it as potentially hazardous. Current calculations predict an especially close approach in 2027, when it will pass within about 390,000 kilometers—almost the same distance as the Moon—making it one of the larger asteroids to come so near our planet in the 21st century. ✨
#asteroids⚡#danger⚡#nearEarth⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌎 Saltwater crocodiles are among the most dangerous animals on Earth. These massive reptiles can exceed 6 meters in length and have the strongest recorded bite force of any living animal—over 16,000 newtons. Saltwater crocodiles are responsible for hundreds of attacks on humans annually throughout Southeast Asia and northern Australia. ✨
#crocodile⚡#danger⚡#reptiles
👉subscribe Interesting Planet
👉more Channels
🌎 Hippos are among the most dangerous large animals in Africa, causing more human deaths annually than lions. Territorial males can attack boats and move surprisingly fast on land, reaching speeds of up to 30 kilometers per hour. ✨
#hippo⚡#wildlife⚡#danger
👉subscribe Interesting Planet
🪐 The asteroid (7335) 1989 JA is classified as a "potentially hazardous asteroid" because it's over 1.8 kilometers wide and its orbit brings it close enough to Earth to be watched carefully by astronomers. In 2022, it made a safe pass at about 4 million kilometers from our planet, but its great size means that any future close approach will always be closely monitored for any change in its path. ✨
#asteroids⚡#danger⚡#nearearthobjects⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌎 The freshwater African Nile crocodile holds a notorious reputation as one of Earth's most dangerous animals, responsible for hundreds of human fatalities yearly. Adult males can reach up to 5 meters in length and exert a bite force exceeding 16,000 newtons—one of the strongest in the animal kingdom. ✨
#crocodile⚡#danger⚡#predators
👉subscribe Interesting Planet
👉more Channels
🌎 Saltwater crocodiles are Earth's largest living reptiles and among the most dangerous animals, capable of ambushing and killing prey as large as water buffalo. Adult males can grow over 6 meters long and weigh up to 1,000 kilograms. ✨
#crocodile⚡#predators⚡#danger
👉subscribe Interesting Planet
🪐 On June 30, 1908, a small asteroid or comet exploded over Tunguska, Siberia, flattening 2,000 square kilometers of forest in an instant. Known as the Tunguska event, this airburst was caused by an object about 50–60 meters wide—large enough to release energy more powerful than the largest nuclear bomb ever detonated, yet leaving no impact crater. ✨
#asteroids⚡#danger⚡#Tunguska⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
Why did yhe 2026 SuperbOwl logo colors match the Emergency Broadcast System colors??? What do they have planned or already know is coming??? #migrateEast#Danger#EmergencyBroadcastSystem#SuperBowl