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

Резултати

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

Пребарај: #ring

当前筛选 #ring清除筛选
Libreware

@libreware · Post #1541 · 10.02.2026 г., 21:04

Super Bowl Ad TRICKING You Into Welcoming Surveillance State! During the Super Bowl, you may have seen a commercial for #Amazon’s #Ring “Search Party” feature, which uses an emotional lost-dog story to encourage adoption of participation in what amounts to a widespread neighborhood #surveillance net. Jimmy points out that the ad masks #privacy risks tied to AI-driven #cameras, data sharing, and Amazon’s broader surveillance ecosystem, including concerns about opt-out defaults and government access. He and Americans’ Comedian Kurt Metzger expand the discussion into a broader critique of social media and smart devices as tools of self-surveillance, suggesting public safety and convenience are being used to justify constant monitoring. Ultimately, it frames the commercial as emblematic of a growing surveillance state presented as benevolent technology. https://www.youtube.com/watch?v=5AJtRDjoXN4 #why

Russian Consulate in Cape Town

@rusconct · Post #2211 · 03.02.2025 г., 06:01

#Victory80 🌟 February 2, 1943, one of the most brutal battles of #WWII and all of history — the Battle of Stalingrad — concluded. For 2️⃣0️⃣0️⃣ days and nights the Battle of Stalingrad raged on the banks of the Don and the Volga rivers, and in the city proper, or rather what was left of it following merciless Nazi bombardments and stubborn defender fighting for every street, alley and house. The battle itself surpassed in scope and intensity all prior battles of #WWII. During that battle, more than 2.1 million people fought on both sides. By the end of June 1942, the Nazis concentrated in the strip of land from Kursk to Taganrog on the front of 600-650 kilometers up to 35% of infantry, over 50% of armour and motorized divisions of the total number of Wehrmacht troops deployed on the Soviet-German front. During the planning of the Stalingrad operation, the enemy had several objectives: to gain a foothold on the Volga River and thus deprive the #SovietUnion of control over one of the most important transportation arteries of the country. The capture of #Stalingrad, according to the assessment of the Nazi military command, would open the way for the Wehrmacht to the Caucasus, where the Germans hoped to obtain the most important resource for making the war machine continue — oil fields. Traditionally, according to the historians, the Battle was divided into two stages: • Defensive phase: from July 17 to November 18, 1942; • Offensive phase: from November 19, 1942 to February 2, 1943. During the first stage, July 17 - November 18, 1942, the Red Army had to conduct defensive operations and engaged the enemy in fierce street battles directly in the city. The forces of the 62nd and 64th Soviet armies, led by Vassily Chuikov, commander of the 62nd Army, engaged the troops of the 6th Army of the Wehrmacht under the command of Lieutenant General Paulus. By mid-November 1942, as a result of stubborn resistance and the deployment of the Red Army reserves favorable conditions were created for launching the counteroffensive. The plan for the operation code-named#Uranus was developed under the leadership of Army General Georgy Zhukov and Colonel General Alexander Vasilevsky. During the large-scale counteroffensive at Stalingrad (November 19, 1942 — February 2, 1943), Soviet forces conducted the operation #Ring, during which the Red Army managed to drive Paulus's 6th Army into a “cauldron” between the Don and Volga rivers. Realizing the futility of further action, by the end of January the Nazi units began to surrender en masse. On January, 31, General Paulus (promoted by Hitler to to General-Field Marshal), together with other German generals and officers at Stalingrad finally surrendered. OnFebruary 2, the last pockets of Nazi resistance were eliminated. The #BattleOfStalingrad ended with a complete victory of the Red Army. For the first time ever the all-consuming Nazi war machine was weighed, measured and found wanting. This marked a turning point not only in the the Great Patriotic War, but that of the entire #WWII. In Stalingrad, Wehrmacht and its auxiliary forces from the Axis lost 1/4 of all troops deployed by the Reich on the Eastern front. Total enemy losses amount to ~1.5 million soldiers and officers. From that moment forward thestrategic initiative was on the side of the Red Army. The Victory in Stalingrad created favourable conditions for further full-scale counteroffensive of Soviet forces to expel the enemy from the Nazi-occupied territory of the USSR. 🌐 The defeat of the bulk of the enemy troops not only shocked the world and significantly raised the international prestige of the Soviet Union and its Armed Forces, but also contributed to the strengthening and tightening of the anti-Hitler coalition. 🎖 Victory in the Battle of Stalingrad was in large achieved through superior strategy and tactics, but also due to mass heroism of Soviet soldiers, officers and hard work of all those on the home front. 112 participants of the Battle were awarded the title of the Hero of the Soviet Union. #WeRemember