Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🪐 Magnetars like Swift J1822.3−1606, discovered in the constellation Sagittarius, create magnetic fields over a trillion times stronger than Earth's—so intense they can distort atoms and transform empty space itself into a strange state called a “quantum vacuum.” These extreme conditions make magnetars some of the most powerful natural magnets ever found, unleashing bursts of high-energy X-rays and gamma rays that briefly outshine everything nearby. ✨
#magnetar⚡#neutronstar⚡#extremes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The magnetar PSR J1745−2900, found near the center of our Milky Way close to Sagittarius A*, showcases magnetic fields so intense they can disrupt atoms and twist space itself. Its field strength is estimated at over a quadrillion times higher than Earth's, making PSR J1745−2900 one of the most extreme magnets in the galaxy and a prime example of how magnetars stretch the laws of physics to their limits. ✨
#magnetar⚡#neutronstar⚡#extremes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Deep in the constellation Carina sits the magnetar 1E 2259+586, a neutron star with a magnetic field so powerful—over 100 trillion times stronger than Earth's—that it can twist and shatter its own crust. When this happens, it releases bursts of high-energy X-rays and gamma rays, briefly outshining entire galaxies before fading back into cosmic silence. ✨
#magnetar⚡#neutronstar⚡#extremes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the constellation Ophiuchus, the neutron star PSR J1846–0258 stunned astronomers when it suddenly switched from behaving like a typical pulsar—flashing regular radio waves—to emitting powerful X-ray bursts, a feature seen in "magnetars," which are neutron stars with ultra-strong magnetic fields. This rare identity shift blurs the line between two of the most extreme types of dead stars, revealing the unpredictable and mysterious nature of cosmic objects. ✨
#neutronstar⚡#magnetar⚡#phenomena⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The magnetar CXOU J171405.7−381031, found in the supernova remnant CTB 37B, is famous for its exceptionally strong magnetic field—over a thousand trillion times more powerful than Earth's. Such intense magnetism can twist the star’s crust, causing violent starquakes and bursts of high-energy radiation that briefly outshine everything else in its region of space. ✨
#magnetar⚡#supernova⚡#neutronstar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 On August 27, 1998, astronomers detected a remarkable gamma-ray burst from the magnetar SGR 1900+14, located about 20,000 light-years away in the constellation Aquila. This event released more than a thousand times the energy of the Sun in just a fraction of a second, making it one of the brightest gamma-ray flashes ever recorded and proving that magnetars—neutron stars with ultra-strong magnetic fields—can unleash explosions powerful enough to briefly outshine entire galaxies. ✨
#gamma-ray-bursts ⚡#magnetar⚡#cosmic-explosions ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Deep in the constellation Vulpecula, the magnetar 1E 2259+586 unleashes magnetic fields so powerful—over 100 trillion times stronger than Earth's—that they can physically warp the star's crust. When these intense magnetic forces crack the surface, they release bursts of high-energy X-rays and gamma rays, briefly making the magnetar outshine every other X-ray source in its region of space. ✨
#magnetar⚡#neutronstar⚡#extrememagnetism⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The magnetar named J1745−2900, discovered near the center of our galaxy close to Sagittarius A*, has one of the most powerful magnetic fields ever measured—enough to disrupt radio signals and, in theory, even deform atoms into thin strings. This type of neutron star is so incredibly magnetic that its field would erase every credit card on Earth from a distance of half the Moon’s span, making J1745−2900 an extreme natural magnet impossible to recreate in any lab. ✨
#magnetar⚡#neutronstar⚡#extremespace⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The magnetar 1RXS J170849.0–400910, located about 18,000 light-years away in the constellation Ophiuchus, is known for its titanic magnetic field, which can reach over 100 trillion times the strength of Earth's. This intense magnetism is so powerful that it can twist the star's crust, triggering sudden bursts of X-rays and gamma rays—brief flashes that outshine entire regions of space before fading into darkness. ✨
#magnetar⚡#Xrays⚡#Ophiuchus⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels