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

Пребарај: #why

当前筛选 #why清除筛选
Libreware

@libreware · Post #1553 · 21.02.2026 г., 05:39

Keep Android Open https://keepandroidopen.org https://f-droid.org/2026/02/20/twif.html During out talks with F-Droid users at FOSDEM26 we were baffled to learn most were relieved that #Google has canceled their plans to lock-down #Android. Why baffled? Because no such thing actually happened, the plans announced last August are still scheduled to take place. We see a battle of PR campaigns and whomever has the last post out remains in the media memory as the truth, and having journalists just copy/paste Google posts serves no one. But Google said… Said what? That there’s a magical “advanced flow”? Did you see it? Did anyone experience it? When is it scheduled to be released? Was it part of Android 16 QPR2 in December? Of 16 QPR3 Beta 2.1 last week? Of Android 17 Beta 1? No? That’s the issue… As time marches on people were left with the impression that everything was done, fixed, Google “wasn’t evil” after all, this time, yay! While we all have bad memories of “banners” as the dreaded ad delivery medium of the Internet, after FOSDEM we decided that we have to raise the issue back and have everyone, who cares about Android as an open platform, informed that we are running out of time until Google becomes the gate-keeper of all users devices. Hence, the website and starting today our clients, with the updates of F-Droid and F-Droid Basic, feature a banner that reminds everyone how little time we have and how to voice their concerns to whatever local authority is able to understand the dangers of this path Android is led to. We are not alone in our fight, IzzyOnDroid added a banner too, more #FDroid clients will add the warning banner soon and other app downloaders, like Obtainium, already have an in-app warning dialogue. #why

Momogram

@momogram_update · Post #1183 · 21.02.2026 г., 09:25

Keep Android Open https://keepandroidopen.org https://f-droid.org/2026/02/20/twif.html During out talks with F-Droid users at FOSDEM26 we were baffled to learn most were relieved that #Google has canceled their plans to lock-down #Android. Why baffled? Because no such thing actually happened, the plans announced last August are still scheduled to take place. We see a battle of PR campaigns and whomever has the last post out remains in the media memory as the truth, and having journalists just copy/paste Google posts serves no one. But Google said… Said what? That there’s a magical “advanced flow”? Did you see it? Did anyone experience it? When is it scheduled to be released? Was it part of Android 16 QPR2 in December? Of 16 QPR3 Beta 2.1 last week? Of Android 17 Beta 1? No? That’s the issue… As time marches on people were left with the impression that everything was done, fixed, Google “wasn’t evil” after all, this time, yay! While we all have bad memories of “banners” as the dreaded ad delivery medium of the Internet, after FOSDEM we decided that we have to raise the issue back and have everyone, who cares about Android as an open platform, informed that we are running out of time until Google becomes the gate-keeper of all users devices. Hence, the website and starting today our clients, with the updates of F-Droid and F-Droid Basic, feature a banner that reminds everyone how little time we have and how to voice their concerns to whatever local authority is able to understand the dangers of this path Android is led to. We are not alone in our fight, IzzyOnDroid added a banner too, more #FDroid clients will add the warning banner soon and other app downloaders, like Obtainium, already have an in-app warning dialogue. #why

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

Libreware

@libreware · Post #1574 · 07.04.2026 г., 12:21

SharedTrace #Python tool for getting additional info by shared link (usernames, avatars, IDs etc). Support TikTok, Instagram, Discord, ChatGPT, Perplexity and other platforms. https://github.com/hondling/sharetrace @cybdetective #socmint#tracking#trackers#stalking#surveillance#why