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

Резултати

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

Пребарај: #drought

当前筛选 #drought清除筛选
Red Nile

@rednile12 · Post #10814 · 20.01.2026 г., 13:25

በ2020ው የዋሽንግተን ረቂቅ የስምምነት ሰነድ አሜሪካ እና ግብፅ እንደ ወጥመድ የተጠቀሙት "DROUGHT" እና "WATER FLOW" ዋሽንግተን ላይ ተደርጎ በነበረው ድርድር የአየር ሁኔታን ተገን አድርገው ግብፅ እና አሜሪካ "Historic Right" የሚለውን የግብፅን የቅኝ ግዛት ትሪክት " #DROUGHT" የሚል ካባ አልብሰው በ2020ው የዋሽንግተን ረቂቅ የስምምነት ሰነድ ውስጥ እንደት እንዳስገቡ እንመልከት ወደ ዋሽግተኑ ረቂቅ የስምምነት ሰነድ ከመሄዳችን በፊት ትራምፕ ጃንዋሪ 16፣ 2026 ላይ “በድርቅ እና ለረጅም ጊዜ ደረቅ ዓመታት ለግብፅ እና ለሱዳን የሚለቀቁ የውሃ ልቀት ሊተነብይ የሚችል ይሆናል” ብሎ ለፍሬንዱ አል ሲሲ የላከውን መልዕክት ስንመረምር መልዕክቱ የተቀዳችው ከረቂቅ ሰነዱ ይሆን🤔? የሚል ጥርጣሬም ያጭራል:: ጥርጣሬውን እንደጥርጣሬ ይዘን👇 በ2020 የዋሽንግተን ረቂቅ ሰነድ ውስጥ የሰፈሩት “ድርቅ” እና “ረዥም ጊዜ ደረቅ ዓመታት” ለሚሉ አባባሎች፤ ኢትዮጵያ አባባሎቹ አደገኛ ወጥመድ ናቸውና ከትርጓሜያቸው ጀምሮ መስተካከል አለባቸው ስትል ተከራክራለች:: 🔻Continued Below @rednile12

Hashtags

Addis Standard

@addisstandardeng · Post #21904 · 01.04.2026 г., 13:07

‘Sharing is off the table’ as #drought reshapes the lives of #Ethiopia’s pastoralists Pastoralists in Ethiopia’s #Somali region say that worsening drought is eroding traditional systems of sharing that once helped communities survive. Historically, Somali pastoralists survived drought through strong social networks. These Indigenous climate adaptations were built on an intricate system of mutual aid. One of the most important systems is known as Gergar, a form of social insurance in which families who lose livestock receive animals from relatives and neighbors to help rebuild their herds. “When people used to lose livestock, others would help them,” says Mohamed Abdi, a lifelong pastoralism advocate and director at Jijiga University’s Institute of Pastoral and Agro-Pastoral Development Studies. “We would move to relatives or sub clan areas, and they shared water and pasture with us.” https://news.mongabay.com/2026/04/sharing-is-off-the-table-as-drought-reshapes-the-lives-of-ethiopias-pastoralists/

Addis Standard

@addisstandardeng · Post #21345 · 09.02.2026 г., 06:51

'Our children are next' fear #Kenyans as #drought wipes out livestock In drought-hit northeastern Kenya, villagers have been forced to drag their dead livestock to distant fields for burning to keep the stench of death and scavenging hyenas away from their homes. Mandera county along Kenya's borders with Ethiopia and Somalia has seen no rain since May and is now on the point of a full-blown water emergency. "I have lost all my cows and goats, and burned them here," Bishar Maalim Mohammed, 60, a resident of Tawakal village, told AFP. In his village, where most are pastoralists relying heavily on their animals, the only remaining bull can no longer stand. He has lain in the same spot for nearly a week, severely dehydrated with bones protruding through his skin, as his owner watches helplessly. https://addisstandard.com/?p=55089

Interesting Planet 🌍

@interesting_planet_facts · Post #492 · 03.08.2025 г., 16:22

🌎 The Madagascan baobab, sometimes called the “upside-down tree,” stores thousands of liters of water in its massive trunk, allowing survival through severe drought. This clever reservoir keeps it lush while nearby plants wilt. ✨ #Madagascar⚡#baobab⚡#drought 👉subscribe Interesting Planet

Reuters: World

@reutersworldchannel · Post #149409 · 15.10.2021 г., 14:23

Northern Kenya drought pushes millions to hunger The lack of rain in northern Kenya means 2.4 million people in the region will struggle to find enough to eat by November, the United Nations World Food Programme says. #News#Reuters#Kenya#drought#food#environment Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149225 · 11.10.2021 г., 17:07

U.N. warns of Madagascar 'climate change famine' Madagascar produces less than 0.01% of global carbon dioxide emissions, but amid a fourth year of drought in the Grand Sud region, the U.N. is warning of a 'climate change famine'. #Madagascar#UN#UnitedNations#ClimateChange#ClimateChangeFamine#GrandSudRegion#Drought#News#Reuters Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖