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

Резултати

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

Пребарај: #fossils

当前筛选 #fossils清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #1009 · 06.11.2025 г., 12:11

🌎 Hidden deep beneath the Yucatán Peninsula in Mexico, the Sistema Sac Actun is the world’s longest underwater cave system. Stretching over 370 kilometers, these flooded limestone tunnels were formed by rainwater dissolving rock over thousands of years. Archaeologists have found ancient human and animal fossils preserved in the caves, including remains over 13,000 years old. ✨ #caves⚡#archaeology⚡#fossils 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1361 · 02.04.2026 г., 12:11

🌎 Horseshoe crabs have remained virtually unchanged for about 450 million years. Despite their name, they are more closely related to spiders than to true crabs. Modern horseshoe crabs can be found along the Atlantic coast of North America and in Southeast Asia. ✨ #animals⚡#evolution⚡#fossils 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #924 · 17.10.2025 г., 15:11

🌎 Living fossils like the chambered nautilus and horseshoe crab have changed little for hundreds of millions of years. The nautilus dates back over 500 million years, and its closest extinct relatives include ammonites, which died out with the dinosaurs. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #855 · 03.10.2025 г., 22:11

🌎 Living fossils like the giant freshwater stingray and the Australian lungfish have remained almost unchanged for over 100 million years, surviving dramatic changes in Earth’s environment. The horseshoe crab’s body plan is so ancient, it first appeared 450 million years ago. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #726 · 11.09.2025 г., 00:22

🌎 Some ancient animals have survived unchanged for millions of years. The coelacanth, once thought extinct, first appeared 400 million years ago and still swims deep ocean waters today. The horseshoe crab dates back over 450 million years, predating dinosaurs and even trees. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet ​

Amazing Geography 🌍

@amazingeo · Post #588 · 23.01.2026 г., 12:31

🌍 In Alaska, some permafrost soils have preserved ancient animal remains, like mammoth bones and fur, for tens of thousands of years—locked in ice until modern thaw reveals them. ✨ #permafrost⚡#tundra⚡#fossils⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #171 · 04.09.2025 г., 00:12

🌍 Permafrost, ground that stays below freezing year-round, traps ancient plant and animal remains. Thawing permafrost in tundra regions is revealing fossils not seen for thousands of years. ✨ #permafrost⚡#tundra⚡#fossils⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #582 · 18.08.2025 г., 13:22

🌎 In the icy waters near Antarctica, the Antarctic feather star unfurls feathery arms up to 20 times its body length to catch drifting food. This ancient sea creature is a living fossil, unchanged for hundreds of millions of years. ✨ #ocean⚡#fossils⚡#wildlife 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #700 · 24.04.2026 г., 20:31

🌍 The White Cliffs of Dover are made of tiny sea fossils compressed over millions of years. Each cliff face erodes by about one centimeter per year as waves steadily wear them down. ✨ #coastline⚡#erosion⚡#fossils⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #431 · 03.11.2025 г., 12:31

🌍 The Mediterranean coastline holds more than 150 million-year-old fossils, often exposed in seaside cliffs by constant wave erosion. Some beach rocks here contain ancient traces of life dating back to the dinosaurs. ✨ #coastlines⚡#fossils⚡#erosion⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #822 · 27.09.2025 г., 15:11

🌎 Alligators are ancient survivors, having changed little in 80 million years. These reptiles outlived the dinosaurs and now inhabit wetlands in the Americas. ✨ #animals⚡#fossils⚡#reptiles 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #513 · 07.08.2025 г., 00:22

🌎 An ancient “rainbow” mineral called ammolite forms from fossilized ammonite shells. With its dazzling reds, greens, and blues, ammolite is one of the world’s rarest gemstones, found mainly in Canada’s Rocky Mountains. ✨ #geology⚡#fossils⚡#gemstones 👉subscribe Interesting Planet

12
ПретходнаСтраница 1 од 2Следна