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 слични објави

Пребарај: #ifj

当前筛选 #ifj清除筛选
Russian MFA 🇷🇺

@MFARUSSIA · Post #28861 · 25.03.2026 г., 12:48

#MartyrsForTruth ⚡️The Russian Union of Journalists has published a report – Inconsistencies in the Public Accounting of Killed Journalists in 2025:: A Comparative Analysis of CPJ, UNESCO and IFJ Materials. 📄 FULL REPORT (PDF/ Telegraph) ❗️ The report is based on open sources and addresses a fundamental question: why do some cases of journalists being killed receive full international visibility, while others – despite being publicly recorded by international organisations such as #UNESCO, the International Federation of Journalists (#IFJ), and a number of international bodies – are effectively omitted from the statistics? The analysis reveals inconsistencies between the Committee to Protect Journalists' (#CPJ) public reporting for 2025 and a number of cases involving Russian journalists whose deaths were recognized by other international bodies. 👉This raises questions not only about the integrity of the record, but about the credibility of the entire international system for documenting journalists’ deaths. The analysis was prompted by the observed discrepancy between the CPJ’s overall reporting on Ukraine for 2025 and a number of cases involving Russian journalists and media workers, whose deaths were recorded and commented on by other international organisations. More specifically, on February 25, 2026, the CPJ reported that 129 journalists and media workers were killed worldwide in 2025 – the highest figure in the organisation’s history. In the same review, the CPJ stated that four journalists were killed in Ukraine in 2025. The organisation’s public materials lists a number of Ukrainian journalists and French photojournalist Anthony Lallican among those cases. ❗️ At the same time, several cases involving Russian journalists and media workers killed in 2025 do not appear in the CPJ’s open-source materials, despite public statements by the IFJ and UNESCO, and, in a number of instances, reporting by Reuters. They include: ▪️Alexander Martemyanov ▪️Alexander Fedorchak ▪️ Alexander Sirkeli ▪️Andrey Panov ▪️Anna Prokofyeva ▪️Ivan Zuev 👉 The key question is not about disputing the figures or removing names already included in international lists. It is whether all comparable cases are being recorded publicly, consistently, and by the same standards. That is why the focus of professional discussion should not be the slogan of “double standards” as such, but the specific gap between the CPJ’s published methodology and what can be observed in its public reporting on a number of 2025 cases. When that consistency is missing – or left unexplained – it raises questions not just about one report, but about the credibility of the entire international system for documenting threats to journalists.

Marx21.it

@marx21news · Post #10186 · 16.04.2026 г., 06:45

🗞️ “Informare non è solo un mestiere. È una condizione della democrazia.” A pochi giorni dal Congresso Mondiale della Federazione Internazionale dei Giornalisti (IFJ) a Parigi, pubblichiamo un'intervista al segretario generale Anthony Bellanger. Un secolo di lotte, dal 1926 a oggi, per l'indipendenza e la dignità della professione. Dai regimi autoritari degli anni '30 ai conflitti odierni in Ucraina, Gaza e Sudan, la posta è sempre la stessa: resistere alla censura, alla precarietà e alla violenza. Oggi i giornalisti sono bersaglio. Più di 3.000 uccisi in 35 anni. Non solo in guerra, ma per aver indagato su corruzione e abusi di potere. La IFJ chiede una Convenzione ONU vincolante per proteggere chi informa. In un mondo di disinformazione e giganti tecnologici, l’etica e la solidarietà internazionale restano le nostre bussole. 👉 Leggi l'intervista completa e scopri le sfide del prossimo congresso https://www.marx21.it/internazionale/giornalismo-etica-e-dignita-una-lotta-secolare/ #Giornalismo#LibertàDiStampa#Etica#IFJ#Democrazia#DirittiUmani

Addis Standard

@addisstandardeng · Post #21662 · 10.03.2026 г., 07:37

News: IFJ condemns killing of journalist in #Kismayo, calls for urgent investigation The International Federation of Journalists (#IFJ) has condemned the killing of #Somali freelance journalist Abshir Khalif Shide Omar, who was shot dead by a police officer in the city of Kismayo in southern #Somalia. According to the IFJ, Omar was killed on 2 March following a brief altercation with a police officer in Kismayo, the commercial capital of the autonomous #Jubbaland region, located about 528 kilometers from #Mogadishu. The IFJ said it joined its affiliate, the National Union of Somali Journalists (#NUSOJ), in condemning the killing and calling for an urgent and thorough investigation into the incident. In a statement, NUSOJ said Omar had been returning from an Iftar gathering with colleagues after editing a program about politicians that was scheduled to be released later that ..... https://web.facebook.com/AddisstandardEng/posts/pfbid0CUPBLiJrwHBnxuTeaq4c3XBuwGLUFaJBRrEfKh76fYSRWke8MXX2wcfBmkJVDJsal