@googlefactss · Post #40777 · 12.03.2026 г., 07:01
A group of jellyfish is called a bloom, swarm, or smack. @googlefactss#nowyouknow
Hashtags
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
Пребарај: #nowyouknow
@googlefactss · Post #40777 · 12.03.2026 г., 07:01
A group of jellyfish is called a bloom, swarm, or smack. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #40758 · 07.03.2026 г., 15:04
Jellyfish move in essentially two ways. They take water in their bell and then squirt it out behind them, which creates a jet of water that moves them forward. They also drift on water currents. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #40710 · 27.02.2026 г., 07:04
Horseshoe crabs are not crabs at all. They are not even crustaceans. Instead, they have their own separate class named Merostomata. They have hardly changed since the age of the dinosaurs, and their closest-living relatives are spiders @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #40525 · 11.01.2026 г., 19:02
Blind people smile even though they have never seen anybody else smile. Facial expressions like smiling are largely innate and biological, not just learned through visual imitation and not learned at all. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39979 · 30.10.2025 г., 08:02
Stan is an ancient Persian word meaning “land” or “nation,” and Kazakh means “wanderer,” “adventurer,” or “outlaw.” Therefore, the name Kazakhstan translates as “Land of the Wanderers. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39972 · 29.10.2025 г., 08:48
In terms of absolute size and in proportion to overall body mass, the human penis is longer and thicker than that of any other primate. For instance the average size of the human penis is 8-10 cm when flaccid and 13-15 cm when erect while gorillas, which are the largest primates, have a penis size of approximately 4 cm in length when erect. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39942 · 23.10.2025 г., 07:58
The colors of fire hydrants give a reasonably accurate picture as to how much water flow and pressure they can provide @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39922 · 13.10.2025 г., 12:57
The position dogs assume when they are inviting other pets to play is called a play bow. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39899 · 03.10.2025 г., 22:04
The historical figure who inspired the Santa Claus legend, Saint Nicholas, was born in Patara, Turkey, in the 3rd century A.D. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39888 · 29.09.2025 г., 17:20
Greek philosopher Aristotle (384–322 BC) thought the heart, not the brain, was the center of mental functions, emotions, and intellect. He considered the heart the core of the body's "psychical fire" and the source of its heat, with the brain's main role being to cool the blood. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #39885 · 29.09.2025 г., 13:02
The al-Qarawiyyin Library in Fez, Morocco is the oldest working library in the world. It was founded in 859 CE by Fatima al-Fihriya. @googlefactss#nowyouknow
Hashtags
@googlefactss · Post #40641 · 09.02.2026 г., 15:02
Napoleon I banned fashion dolls because he was nervous they could be used to send secret messages. [Read more] @googlefactss#nowyouknow#history
Hashtags