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

Резултати

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

Пребарај: #conservation

当前筛选 #conservation清除筛选
Amazing Geography 🌍

@amazingeo · Post #670 · 23.03.2026 г., 20:31

🌍 The Madagascar and Indian Ocean Islands hotspot is home to over 11,000 plant species, and about 80% of them exist nowhere else—an extraordinary concentration of unique life. ✨ #biodiversity⚡#islands⚡#conservation⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #566 · 15.08.2025 г., 18:22

🌎 On the plains of Mongolia, the Przewalski’s horse gallops wild—the only truly wild horse species left on Earth. Unlike domestic horses, it has never been tamed, boasting a stocky build, upright mane, and a unique history of survival after near-extinction in the wild. ✨ #wildlife⚡#conservation⚡#mammals 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #368 · 13.10.2025 г., 18:31

🌍 Costa Rica’s biodiversity hotspot holds more plant species in just one hectare than most European countries have nationwide, showcasing how concentrated life can be in these rare regions. ✨ #biodiversity⚡#conservation⚡#tropics⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

URA Singapore

@URASingapore · Post #877 · 17.06.2024 г., 01:15

Selamat Hari Raya Haji! ✨ In the first episode of our new series ‘Your POV’, see through the eyes – and lens – of photographer @izmyphotos📸 We’ll celebrate Hari Raya Haji while exploring Masjid Alkaff Upper Serangoon – a recipient of the Architectural Heritage Award (AHA) in 2015 for retaining the vision of the original architects 🕌 Curious about other AHA winners? 👉 Check it out here: go.gov.sg/AHA2024TG #ExploreSingapore#Conservation#ArchitectureSG

Amazing Geography 🌍

@amazingeo · Post #288 · 23.09.2025 г., 18:31

🌍 The Sundaland region in Southeast Asia is a biodiversity hotspot where over 15,000 plant species are found, nearly half of which exist nowhere else on Earth. ✨ #biodiversity⚡#hotspots⚡#conservation⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #173 · 04.09.2025 г., 09:12

🌍 The Eastern Arc Mountains in East Africa are a biodiversity hotspot where 75% of the area's plant species exist nowhere else on Earth—making it one of the planet’s most unique natural vaults. ✨ #biodiversity⚡#conservation⚡#ecology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #571 · 16.08.2025 г., 16:22

🌎 In the Gulf of California, the vaquita porpoise is the world’s rarest marine mammal, with fewer than 10 left. Its shy nature and distinctive dark eye rings make it unique, but illegal fishing nets threaten its survival. ✨ #vaquita⚡#conservation⚡#ocean 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #464 · 30.07.2025 г., 02:22

🌎 The Svalbard Global Seed Vault, buried deep in a Norwegian mountain, stores over a million seed varieties as a backup for global agriculture—safeguarding food diversity for future generations. ✨ #biodiversity⚡#conservation⚡#vault 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #387 · 22.07.2025 г., 17:22

🌎 The black robin of New Zealand bounced back from just five birds left in the world in 1980—thanks to devoted conservation, their population is now stable. This comeback highlights how careful human intervention can save even the rarest species from extinction. ✨ #conservation⚡#wildlife⚡#recovery 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #963 · 25.10.2025 г., 12:11

🌎 The Okavango Delta in Botswana transforms each year from dry savanna to a maze of wetlands due to annual flooding, but modern irrigation and water extraction upstream have reduced natural flows. This human impact threatens a UNESCO World Heritage site that supports over 400 bird species and large populations of elephants and hippos. ✨ #conservation⚡#wetlands⚡#Africa 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #154 · 01.09.2025 г., 03:12

🌍 Nearly 10 million hectares of forest are lost each year, but new satellite tracking helps spot illegal logging and monitor regrowth, making large-scale forest recovery more achievable than ever. ✨ #deforestation⚡#satellites⚡#conservation⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

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