TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 776 слични објави

Пребарај: #astronomy

当前筛选 #astronomy清除筛选

So our son got a telescope for his birthday. But as he is way too young to use it, guess who can now take a (not perfect) look at the old gods. Above you see an image of the moon shot with a mobile cam through the lens. I know, poor quality. But I will improve. If you live in Central Europe and have clear skies, look south now and watch Jupiter and Saturn following the Moon. Jupiter is a bright object some degrees to the east from the Moon, while Saturn follows Jupiter as a tiny speck in the sky. #astronomy @EuropeanTribalism

Hashtags

On comets This is an image of the comet C/2006 P1, commonly known as McNaught. Scientists observed its tail modifying attributes of the solar wind, which is impossible by the standard model, which claims that comets are 'dirty snowballs'. In reality, comets are charged rocks which spend most of their time in the outer regions of the solar system, where they accumulate a negative charge until they start their journey into the center of the solar system. Their tails are visible electric discharge phenomena. To recognize the electrical nature of comets, means recognizing the electrical nature of the universe and is key in understanding spirituality. #astronomy#comets @EuropeanTribalism

Amazing Geography 🌍

@amazingeo · Post #643 · 21.02.2026 г., 20:31

🌍 Earth travels around the Sun at about 107,000 kilometers per hour, yet we don’t feel it thanks to the planet’s steady movement and protective atmosphere. ✨ #Earth⚡#solarplanet⚡#astronomy⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1148 · 20.12.2025 г., 22:11

🌎 A star called KIC 8462852, also known as Tabby's Star, has shown highly unusual, unpredictable dips in brightness. Unlike typical stars, its brightness sometimes drops by up to 22%. Astronomers have ruled out planets and suspect dust clouds or fragments from a disintegrating comet might be causing the effect. ✨ #astronomy⚡#space⚡#mystery 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #673 · 02.09.2025 г., 03:22

🌎 Astronomers have detected rapid radio bursts—millisecond-long signals from distant space. These intense pulses hint at extreme events, like collapsing stars or magnetars, yet their exact origin remains one of space’s most intriguing mysteries. ✨ #astronomy⚡#space⚡#mysteries 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #647 · 28.08.2025 г., 20:22

🌎 Space isn’t silent—astronomers have recorded eerie “whistles” and “choruses” from planets like Jupiter. These radio waves, caused by charged particles moving through magnetic fields, are transformed into sound waves we can hear when played back on Earth. The haunting tunes of space reveal hidden cosmic activity all around us. ✨ #astronomy⚡#space⚡#mysteries 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1398 · 13.05.2026 г., 12:11

🌎 Saturn is famous for its bright rings, but these rings are mostly made of tiny bits of ice and rock, ranging from dust-sized grains to pieces several meters across. Scientists estimate the rings are relatively young—no more than 400 million years old. ✨ #space⚡#planets⚡#astronomy 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1291 · 13.02.2026 г., 22:11

🌎 Some planets in our Solar System have extreme day lengths. Venus rotates so slowly that a single day there lasts 243 Earth days, making its day longer than its year. Mercury also has unusual days—one day-night cycle equals 176 Earth days. ✨ #planets⚡#astronomy⚡#space 👉subscribe Interesting Planet 👉more Channels ​

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••6465
ПретходнаСтраница 1 од 65Следна