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

Пребарај: #escapes

当前筛选 #escapes清除筛选
bjjfanaticsinstructionals

@bjjfanaticsinstructionals · Post #1919 · 17.02.2026 г., 03:39

🔥NEW RELEASE🔥 😁Systematically Dismantling Octopus Guard & Other Low-Percentage Moves by Gordon Ryan😁 ➡️Systematically Dismantling Octopus Guard & Other Low-Percentage Moves is Gordon Ryan’s blueprint for shutting down hype-driven positions and forcing your opponents back into reality. ➡️Gordon also addresses a range of increasingly popular “low-percentage” techniques that are flooding competitions and social media. Instead of simply dismissing them, he shows you exactly why they fail — and how to counter them with tight mechanics, superior positioning, and intelligent pressure. $349😍$24.99😍 ❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️ 📱Payment: 📱📱📱 💰Submeta FOR FREE 👑MasterClass ✈️@bjjfanaticsinstructionals #GordonRyan#Escapes#NoGi#NewWave 💁‍♀️Buy 💁‍♀️

bjjfanaticsinstructionals

@bjjfanaticsinstructionals · Post #1829 · 17.06.2025 г., 14:04

🔥NEW RELEASE🔥 😁Can't Keep Me Down Escaping Pins by Garry Tonon😁 ➡️Known worldwide for his fearless approach and jaw-dropping escapes, Garry thrives in positions others fear. His unique system is built on embracing pressure and turning precarious situations into opportunities to regain control and dominate. ➡️In this must-have release, Garry breaks down his world-class escape strategies, showcasing the exact techniques that have defined his career, including his unforgettable battle with Palhares — a match that cemented his reputation as possibly the greatest escape artist in Brazilian Jiu-Jitsu history. ➡️Whether you’re caught under a heavy mount or trapped in a brutal pin, Can’t Keep Me Down teaches you how to stay calm, create space, and execute escapes that flip the script and put you in the driver’s seat. If you want to add a relentless, never-say-die mindset and world-class escapes to your arsenal, this instructional is your blueprint. $197😍$14.99😍 ❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️ 📱Payment: 📱📱📱 💰Submeta FOR FREE 🌈UFC Picks 👑MasterClass ✈️@bjjfanaticsinstructionals #GarryTonon#Escapes#NoGi#NewWave 💁‍♀️Buy 💁‍♀️

bjjfanaticsinstructionals

@bjjfanaticsinstructionals · Post #1942 · 22.04.2026 г., 16:15

🐈‍⬛NEW RELEASE 🐈‍⬛ 🐈‍⬛Drill for Skill Chest to Chest Pin Escapes by Placido Santos 🐈‍⬛ 🐈‍⬛In Drill for Skill: Chest-to-Chest Pin Escapes, Placido Santos delivers a complete escape system that combines world-class instruction with structured drilling progressions—so you don’t just understand escapes… you can execute them when it matters. 🐈‍⬛Known to many as John Danaher’s trusted uke, Placido is far more than that—he’s a high-level competitor and one of the most detail-oriented students of Danaher’s system, alongside names like Gordon Ryan, Giancarlo Bodoni, and Brian Glick. $197 🐈‍⬛$14.99 🐈‍⬛ ❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️ 📱Payment: 📱📱📱📱 💰Submeta FOR FREE 👑MasterClass ✈️@bjjfanaticsinstructionals #PlacidoSantos#Escapes#NoGi#NewWave 🐈‍⬛Buy 🐈‍⬛

bjjfanaticsinstructionals

@bjjfanaticsinstructionals · Post #1843 · 17.07.2025 г., 23:48

😁Ninja Escapes by Kenta Iwamoto😁 ➡️Unlock the secrets to flawless back escapes and turtle escapes with Ninja Escapes by Kenta Iwamoto — a masterful Brazilian Jiu-Jitsu instructional series designed to elevate your defensive game ➡️Whether you find yourself trapped in a tight back control or stuck in the turtle position, this detailed program breaks down escape techniques with precision and clarity. ̶$̶7̶9̶😍$9.99😍 ❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️ 📱Payment: 📱📱📱 💰Submeta FOR FREE 🌈UFC Picks 👑MasterClass ✈️@bjjfanaticsinstructionals #KentaIwamoto#Escapes#NoGi#BTeam 💁‍♀️Buy 💁‍♀️

bjjfanaticsinstructionals

@bjjfanaticsinstructionals · Post #1893 · 18.12.2025 г., 00:35

🔥NEW RELEASE🔥 😁Pins And Dominant Position Escape Engineering by Adam Wardziński😁 ➡️Turn the Tide from the Bottom — Learn Elite-Level Escape Systems from One of the Most Battle-Tested Gi Competitors in the World ➡️In Pins and Dominant Position Escape Engineering, Adam breaks down his battle-tested escapes from side control, mount, back control, knee-on-belly, and more — all with the clarity, detail, and realism you'd expect from someone who’s done it at the highest level. $147😍$11.99😍 ❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️ 📱Payment: 📱📱📱 💰Submeta FOR FREE 👑MasterClass ✈️@bjjfanaticsinstructionals #AdamWardzinski#Escapes#Gi#IBJJF 💁‍♀️Buy 💁‍♀️

djangoproject

@djangoproject · Post #436 · 09.09.2017 г., 15:24

https://pypi.python.org/pypi/bleach Bleach is a allowed-list-based #HTML sanitizing library that #escapes or #strips markup and attributes. Bleach can also linkify text safely, applying #filters that #Django’s urlize filter cannot, and optionally setting rel attributes, even on links already in the text. #Bleach is intended for sanitizing text from untrusted sources. If you find yourself jumping through hoops to allow your site administrators to do lots of things, you’re probably outside the use cases. Either trust those users, or don’t.