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

Резултати

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

Пребарај: #razdolnoye

当前筛选 #razdolnoye清除筛选
DruschbaFM - English

@druschbaFm_en · Post #52278 · 19.03.2025 г., 08:04

⚡️ 🇷🇺 🇺🇦⚔️ Ukraine Fronts on the Morning of 19 March⚡️ 🔴#Sumy Direction: 🔴In #Sudzha Sector, to the west in #Ukraine, fights in and around #Zhuravka. To the southeast... 🟡 In #Basovka, the RFAF have advanced and the battle has shifted to the southern settlement part. 🟡 In #Kursk region, the battles for the villages of #Gogolevka and #Guyevo continue. 🟡#Oleshnya and #Gornal remain under AFU control. 🗺 Map 1; added arrows show the mentioned locations, black contested 🔴 In #KrasnayaYaruga Sector, the AFU crossed the border in the area of ​​the #Demidovka, #Grafovka and #Prilesye villages south of #Sudhza in #Belgorod region. Several attack waves have been stopped by destroying armoured vehicles. The AFU remnants tried to get a foothold. Fights on Russian territory, especially towards #Demidovka with tank support continued. According to the latest unconfirmed report, the invaders have withdrawn to their initial positions in #Sumy region. 🎬 Video 1 🗺 Map 2 🔴#Kharkov Direction: 🔴In #Liptsy Section, the AFU counterattacked unsuccessfully in the settlement area of #​​Glubokoye. 🔴 In #Volchansk Section, the battle for the city continues. 🔴#Svatovo Front: 🔴 In #Kupyansk Sector, to the north, the RFAF are advancing from #Topoli southwestwards towards #Kamenka, the eastern approaches of which are also attacked. Furthermore Russian troops advance from the south on the village. 🟡 Near #Krasnoye1st(Pervoye), to the southwest, Russin units are advancing on the settlement. 🟡#Figolevka, located further southwest, has been recaptured by the AFU. 🟡 North of #Kupyansk, Russian units are expanding the bridgehead northeast of #Kondrashovka. 🟡 Northeast of #Kupyansk, the AFU counterattacks in the area of #Petropavlovka. 🔴 In #Borovaya Sector, fierce fighting in the northern outskirts of #Boguslavka continues. 🔴In #Liman Sector, Russian troops have advanced to #BalkaZhuravka's northern settlement outskirts and continue to attack in the westerly direction. 🟡 North of #Torskoye, positional battles are taking place. 🔴In #Seversk Sector, fights in the area of #Bologorofka (#LPR) continue. The AFU still hold positions on the Chalk Quarry (White Mountain) south of the village. 🟡 In #Verkhnekamenskoye, fights for the centre. 🔴#ChasovYar Direction: 🔴In #ChasovYar Sector, fierce battles continue. The AFU counterattacks. 🔴In #Toretsk Sector, the situation is unchanged. 🔴#Pokrovsk Direction: 🔴 South of the City, heavy battles and counterattacks continue. The situation is dynamic. 🟡#Shevchenko has been recaptured by Russian forces. The AFU counterattacks. 🟡 In #Peschanoye, the same situation as for #Shevchenko. 🟡 In #Kotlino, the northwestern outskirts and the cemetery area are embattled. 🔴 On the left Flank, the battle for #Udachnoye continues. 🔴#Komar Direction: 🔴In #Konstantinopol Sector, west of #Andreyevka, the AFU have pushed back Russian assault groups, which attacked towards #Alekseyevka. 🟡 In #Konstantinopol, the RFAF lost control over the village. The AFU have advanced into its centre. 🎬 Video 2 🟡 South of #Konstantinopol, the RFAF expanded their control zone by more than 1 km. The battle for the village continues. 🟡 From #Razdolnoye, Russian units advanced northwards towards #Razliv and #Bogatyr. 🔴 In #Komar Sector, northwest of #VelikayaNovosyolka, the RFAF are building on their success at #Burlatskoye. 🔴#Zaporozhye Direction: 🔴In the #Orekhov Section, we have to clarify that according to objective evidence data, #Shcherbaki, #MalyeShcherbaki and #Stepovoye are still contested. 🔴 In #Kherson Direction, no changes. 💥#OldRussia: 🔵 In #Krasnodar Territory, the AFU struck the 'Kavkazskaya Oil Transshipment Point.' This, after the Trump - Putin call. 🎞 Video 1 Source; 🎞 Video 2 Source 🗺 Maps @olegtsarov 📋 Sources: CC; Tsarov; ⚡️2M; 🇺🇦Fiend; 😼Kotenok 🕰19 Mar 2025; 06:43 GMT+3; #smo 📱 Join GLOBAL DEPTH to boost your TG Feed 💬Welcome to Military Chat & Ukraine Observer 🇺🇦On Ukraine Observer you will find your daily independent Ukraine War Battle Update