Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Berachain's Infrared Raises $14 Million
Berachain's liquid staking protocol, Infrared, successfully raised $14 million in a Series A token round. The funding aims to support its DeFi initiatives. Read more here: The Block
#DeFi#Berachain#Infrared#Crypto#Investments#Funding#VC
🪐 In 2023, astronomers discovered a free-floating planet called WISEA J110125.95+540052.8, drifting alone about 100 light-years from Earth. Unlike planets tied to stars, rogue planets like this one travel through the galaxy in darkness, warmed only by the faint heat left over from their formation and detectable mainly in infrared light—a reminder that not all worlds need a sun to wander the cosmos. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Milky Way may be home to countless rogue planets—worlds that travel alone, not bound to any star. One such loner, called WISEA J083011.95−614123.5, was spotted using infrared telescopes as it drifts in perpetual night, offering a glimpse into what planets look like when cut off from the warmth and light of a sun. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers estimate there could be billions of rogue planets—planets not bound to any star—drifting through our galaxy in darkness. One example, PSO J318.5-22, floats alone about 80 light-years from Earth, glowing faintly in infrared because it holds onto leftover heat from its formation, even though it has no sun to warm it. ✨
#rogueplanets⚡#galaxy⚡#infrared⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The rogue planet PSO J318.5-22, located about 80 light-years away in the constellation Capricornus, drifts alone through space without a star to call home. Unlike planets that orbit a sun, PSO J318.5-22 glows faintly in infrared from the warmth left over from its formation, making it a true cosmic wanderer and one of the few planetary-mass objects visible in the dark between the stars. ✨
#rogueplanets⚡#exoplanets⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed distant galaxies like MACS1149-JD1 forming stars much earlier than expected, showing that galaxy building blocks were already in place just 500 million years after the Big Bang. By capturing infrared light, Webb can see through cosmic dust and uncover the birth of some of the universe’s first stars, helping scientists understand how the cosmos evolved from darkness to a landscape filled with galaxies. ✨
#Webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed the most detailed images yet of the galaxy cluster SMACS 0723, showing thousands of galaxies and ancient starlight that traveled over 4.6 billion years to reach us. Webb’s infrared vision lets us peer through dust and see cosmic structures, such as warped arcs of light caused by gravitational lensing—where the cluster’s mass bends and magnifies even more distant galaxies hiding behind it. ✨
#galaxies⚡#infrared⚡#lensing⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The James Webb Space Telescope stunned astronomers by capturing images of the faintest, most distant galaxies ever seen—like GLASS-z13, which formed when the universe was only about 300 million years old. Webb’s infrared eyes pierce cosmic dust, making it possible to observe galaxies and stars that existed just after the Big Bang, revealing clues about how the first stars and galaxies came to life. ✨
#webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Near the center of our Milky Way, a cluster of young, massive stars known as the Quintuplet Cluster exists amid clouds of dust, virtually hidden from optical telescopes. Infrared observations have revealed these colossal stars, including the enigmatic "Pistol Star," which burns with a luminosity 1.6 million times brighter than our Sun and sheds mass in powerful, mysterious outbursts. ✨
#QuintupletCluster⚡#PistolStar⚡#infrared
👉subscribe Universe Mysteries
🚀 Infrared to Unlock 27.64 Million Tokens on April 17
Infrared (IR) is set to unlock approximately 27.64 million tokens on April 17 at 0:00 UTC+8. According to ChainCatcher, this information comes from the Web3 asset data platform RootData's token unlocking data. The unlocked tokens are valued at around $1.01 million.
#Infrared#tokenunlocking#Web3#ChainCatcher#RootData#cryptocurrency#April17#digitalassets