Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#PPOD: Neptune 🔵
NASAVoyager 2 made its closest approach to #Neptune in 1989, flying by 4,950 km above its cloud tops. It is still the only spacecraft to have visited the planet! The mission revealed 6 new moons, rings, and geysers erupting from the moon Triton. This Voyager 2 image of Neptune, processed by Kevin Gill, was captured on Aug. 31, 1989.
Credit: NASANASAJPLCaltech / Kevin M. Gill
Source: @SETIInstitute
@EverythingScience
🌎 Neptune’s largest moon, Triton, orbits in the opposite direction to its planet’s rotation—a rare trait called a retrograde orbit. Scientists believe Triton was once a separate icy object captured by Neptune’s gravity around 4 billion years ago. ✨
#planets⚡#astronomy⚡#Neptune
👉subscribe Interesting Planet
👉more Channels
🌎 Neptune, the outermost giant planet, has the fastest winds in the Solar System—reaching up to 2,100 kilometers per hour, faster than a speeding jet. ✨
#planets⚡#astronomy⚡#Neptune
👉subscribe Interesting Planet
👉more Channels
В интернете появились снимки новых лун Урана и Нептуна и чуть больше связанных с ними деталей.
Одна из нептунианских - S/2021 N1 - самый тусклый спутник планеты, когда-либо открытый с Земли: в период противостояний блеск объекта лишь незначительно выше 27-й зв. вел.; объект не бросается в глаза даже на вот этом суммарном фото.
Вся троица - далёкие от своих планет нерегулярные объекты, очевидно, захваченные гравитацией гигантов тела. Тот же S/2021 N1 ещё и обращается вокруг Нептуна за 27.4 года, что также бьёт рекорд спутника Несо (26.7 года) - 60-км тела на орбите всё того же Нептуна (об этом здесь и тут).
****
Согласно традициям наименования в системах ледяных гигантов, новая луна Урана будет названа в честь героя из книг У. Шекспира или А. Поупа. Зеледеневшие же камешки на орбите Нептуна (как это принято для нерегулярных лун 8-й планеты) получат имена в честь нереид - морских нимф из древнегреческой мифологии (их есть с запасом, пока ещё хватит).
#moons#Uranus#Neptune
🪐 The exoplanet LTT 9779b, discovered about 260 light-years away in the constellation Sculptor, is known as an "ultra-hot Neptune" because it orbits its star so closely that its dayside temperature climbs above 1,700°C—hot enough to vaporize metals. Despite these extreme conditions, observations with the Hubble and Spitzer telescopes have revealed a reflective, metallic atmosphere loaded with silicate (rock-forming mineral) clouds, making this planet a shimmering furnace world unlike any found in our solar system. ✨
#exoplanets⚡#extremes⚡#neptune⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌎 On Neptune’s largest moon Triton, geysers of nitrogen ice erupt from beneath the surface, shooting plumes up to 8 kilometers high into the tenuous atmosphere. These cryovolcanic eruptions are driven by sunlight warming a thin layer of transparent ice, a unique phenomenon that shapes Triton's mysterious, dark-streaked terrain. ✨
#Triton⚡#cryovolcanism⚡#Neptune
👉subscribe Universe Mysteries
🪐 On Triton, Neptune's largest moon, icy volcanoes known as cryovolcanoes have been observed erupting plumes of nitrogen gas many kilometers high. This frigid world’s surface is scattered with dark streaks—evidence of these geysers venting from below, hinting at surprising geologic activity beneath its frozen crust. ✨
#Triton⚡#cryovolcanoes⚡#Neptune
👉subscribe Universe Mysteries
🪐 On Neptune’s moon Triton, geysers erupt through its icy crust, blasting nitrogen gas more than 8 kilometers above the surface. These plumes create dark streaks and ever-changing patterns on Triton's frozen landscape, transforming the distant moon into one of the most dynamic worlds in the outer solar system. ✨
#Triton⚡#geysers⚡#Neptune
👉subscribe Universe Mysteries
🪐 Neptune’s moon Proteus, one of the largest moons in the outer solar system, may hide a subsurface ocean beneath its dark, blocky surface. Studies of Proteus’s density and orbital behavior suggest that internal heat from tidal forces—gravitational squeezing by Neptune—could keep water liquid deep inside, making Proteus a surprising addition to the list of possible ocean worlds. ✨
#moons⚡#oceans⚡#neptune⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Neptune’s internal heat keeps this giant planet surprisingly active, releasing more than twice as much energy as it receives from the Sun. This extra energy drives Neptune’s fierce storms and the fastest winds in the solar system, revealing that giant planets can be turbulent worlds even in the freezing dark far from their star. ✨
#Neptune⚡#giantplanets⚡#storms⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The giant planet Neptune, about 17 times heavier than Earth, has the fastest winds in the solar system, reaching speeds over 2,000 kilometers per hour. These icy, supersonic winds zip through Neptune's blue methane clouds, creating enormous, swirling storms that can dwarf our entire planet. ✨
#Neptune⚡#giantplanets⚡#storms⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The giant planet Neptune radiates more energy into space than it receives from the Sun, which is surprising given its great distance from our star. Scientists think this extra heat may come from leftover warmth trapped during Neptune's formation or from slow processes deep within its icy, swirling interior, making Neptune a truly mysterious world at the edge of our solar system. ✨
#Neptune⚡#giantplanets⚡#solarystem⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels