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

Резултати

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

Пребарај: #rivers

当前筛选 #rivers清除筛选
EKOLOG.UZ| ENG

@ekologuzenglish · Post #11880 · 11.03.2026 г., 10:02

#Rivers SyrDarya and AmuDarya on the brink: water scarcity is reshaping regional policy The water-energy crisis in Central Asia is becoming one of the key challenges for the region, including Uzbekistan. According to Kassym-Jomart Tokayev, water availability per capita in the region has decreased by nearly 30% over the past 20 years. Climate change is intensifying the pressure: glaciers in the Pamir and Tien Shan mountains, which feed the Amu Darya and Syr Darya rivers, are rapidly melting. An additional source of concern is the construction of the Qosh Tepa Canal in Afghanistan, which could significantly reduce the flow of the Amu Darya and affect water supply in Uzbekistan and Turkmenistan. The situation is further complicated by an outdated water management system inherited from the Soviet era. Previously, a “water-for-energy” mechanism functioned in the region: Kyrgyzstan and Tajikistan stored water in summer for irrigation needs in Uzbekistan, Kazakhstan and Turkmenistan, receiving energy resources in winter in return. After the collapse of the Soviet Union, this system largely broke down. Today the situation is further complicated by large hydropower projects such as Rogun Dam and Kambarata-1 Hydropower Plant. While these projects strengthen the energy independence of upstream countries, they also raise concerns among downstream states, including Uzbekistan. Experts say the region now faces a choice: escalating water conflicts or strengthening cooperation. For Uzbekistan, water is directly linked to food security, agriculture, and environmental stability. One proposed solution is the creation of a new regional mechanism for managing transboundary water resources and the joint implementation of water-saving technologies. Without such cooperation, water scarcity could become a major challenge for the sustainable development of the entire Central Asian region. 💧🌍 ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

Wallpapers & proverbs

@wal_pep · Post #269 · 24.02.2025 г., 19:46

#Nature #Rivers Amazon's Meeting of Waters Dual-Toned Rivers of Amazon Experience the mesmerizing natural phenomenon at the 'Meeting of Waters’ near Manaus. Here, the dark Rio Negro and the lighter Amazon River flow in parallel, refusing to mix for miles, creating a stunning dual-toned effect. The surrounding landscape features a prominent plateau and mesa, adding to the dramatic beauty of this unique confluence. The vibrant sunset enhances the contrasting colors of the rivers, making it a truly unforgettable sight. This natural wonder showcases the power and beauty of the Amazon rainforest.

Amazing Geography 🌍

@amazingeo · Post #193 · 07.09.2025 г., 13:12

🌍 The world’s shortest river, the Roe River in Montana, flows only about 61 meters from its source to its mouth. Despite its tiny length, it’s officially recognized as a river. ✨ #rivers⚡#hydrology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1205 · 08.01.2026 г., 22:11

🌎 Deep in the Brazilian rainforest, the Encontro das Águas marks where the dark Rio Negro meets the sandy Amazon River. The two rivers flow side by side for 6 kilometers without mixing due to differences in temperature, speed, and density. ✨ #mysteries⚡#rivers⚡#Brazil 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #589 · 23.01.2026 г., 20:31

🌍 The Amazon River’s water travels over 6,400 kilometers from Andes glaciers to the Atlantic, but some of its rain comes from clouds recycled multiple times through plant evaporation along the journey. ✨ #hydrology⚡#rivers⚡#rainforest⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #287 · 23.09.2025 г., 15:31

🌍 Rivers in the Amazon basin recycle rainwater so efficiently that a single water droplet may fall as rain and evaporate back into the sky up to seven times before leaving the forest. ✨ #hydrology⚡#rainforest⚡#rivers⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #367 · 13.10.2025 г., 15:31

🌍 Water trapped as snow and ice in the Himalayas slowly melts each spring, feeding rivers that bring life to billions across Asia. This seasonal meltwater is key to the region’s water cycle. ✨ #hydrology⚡#rivers⚡#glaciers⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #611 · 03.02.2026 г., 20:31

🌍 The Lena River in Siberia creates the largest natural river delta in the Arctic, spreading into thousands of channels and wetlands that provide vital nesting grounds for millions of migratory birds. ✨ #rivers⚡#wetlands⚡#Arctic⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #520 · 17.12.2025 г., 20:31

🌍 Germany’s Upper Middle Rhine Valley is a UNESCO heritage site where castles, vineyards, and medieval villages line steep riverbanks. Its landscape tells centuries of human and natural interaction. ✨ #heritage⚡#landscape⚡#rivers⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #653 · 06.03.2026 г., 20:31

🌍 Africa’s Lake Victoria is the largest tropical lake in the world. Its outflow forms the start of the Nile River, which journeys over 6,600 kilometers north to the Mediterranean Sea. ✨ #lakes⚡#rivers⚡#Africa⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

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