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

Резултати

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

Пребарај: #distro

当前筛选 #distro清除筛选
Linuxgram 🐧

@linuxgram · Post #18038 · 12.03.2026 г., 05:50

📰 AlmaLinux 9 and 10 Gain Official NVIDIA CUDA Support NVIDIA now officially supports AlmaLinux for CUDA workloads, with driver and userspace packages available in the distro's repositories. 🔗 Source: https://linuxiac.com/almalinux-9-and-10-gain-official-nvidia-cuda-support/ #distro

Hashtags

Linuxgram 🐧

@linuxgram · Post #18602 · 28.04.2026 г., 14:55

📰Most Linux regret is actually distro regret, and you probably gave up too soon Let's say I'm introducing ice cream to an alien. I get a cone, put a dollop of vanilla ice cream onto it, and hand it over. The alien gives the ice cream a lick, says it doesn't like the flavor, and then states that, as a result, ice cream just isn't for them. Of course, people wouldn't allow the alien to believe that all ice creams taste bad because it didn't like the vanilla flavor; instead, they'd recommend different flavors of ice creams and... 🔗 Source: https://www.xda-developers.com/linux-regret-actually-distro-regret/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18595 · 28.04.2026 г., 09:56

📰IPFire 2.29 Core Update 201 Linux Firewall Distro Released with DNS Firewall IPFire 2.29 Core Update 201 hardened Linux firewall distro is now available for download with DNS Firewall, Intrusion Prevention System improvements, updated components, and other changes. 🔗 Source: https://9to5linux.com/ipfire-2-29-core-update-201-linux-firewall-distro-released-with-dns-firewall #distro#linux

Linuxgram 🐧

@linuxgram · Post #18557 · 24.04.2026 г., 13:04

📰 Tails 7.7 Anonymous Distro Adds Detection of Outdated Secure Boot Certificates Tails 7.7 anonymous Linux distribution is now available for download with automatic detection of outdated Secure Boot certificates, Tor Browser 15.0.10, and other changes. 🔗 Source: https://9to5linux.com/tails-7-7-anonymous-distro-adds-detection-of-outdated-secure-boot-certificates #distro#linux

Linuxgram 🐧

@linuxgram · Post #18309 · 04.04.2026 г., 13:31

📰 This lightweight Linux distro is what old hardware has been waiting for Void Linux won’t be the right distro for everyone, but on old hardware, its lean design can feel like a second life. 🔗 Source: https://www.xda-developers.com/lightweight-linux-distro-what-old-hardware-waiting-for/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18160 · 23.03.2026 г., 18:55

📰 Every gaming Linux distro is about to share the same foundation, and it could change everything We finally have an answer to Linux gaming's fragmentation problem. 🔗 Source: https://www.xda-developers.com/every-gaming-linux-distro-share-the-same-foundation/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18085 · 17.03.2026 г., 09:54

📰 Ageless Linux Emerges to Protest OS-Level Age Verification Laws And thankfully, it's more than just a Linux distro without age verification. 🔗 Source: https://feed.itsfoss.com/link/24361/17300603/ageless-linux #linux#distro

Linuxgram 🐧

@linuxgram · Post #17982 · 05.03.2026 г., 15:18

📰MX Linux 25 may be the best distro for old PCs that nobody talks about If you have an old laptop you're not ready to throw away yet, MX Linux may just be the best way to give it a new life. 🔗 Source: https://www.xda-developers.com/mx-linux-25-may-be-best-distro-old-pcs-nobody-talks-about/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #17917 · 27.02.2026 г., 13:44

📰 Bazzite triples its userbase in 8 months as gamers seek a Windows alternative People have begun to wake up to the idea that, in some situations, installing a gaming-oriented Linux distro will give you a better experience than Windows 11. Once pinned as the one operating system you don't want to use if you care about gaming, Linux has since come leaps and bounds with tech like Proton that allows games to run on the FOSS operating system without the game's developers lifting a finger. 🔗 Source: https://www.xda-developers.com/bazzite-triples-its-userbase-in-8-months-as-gamers-seek-a-windows-alternative/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #17911 · 26.02.2026 г., 21:23

📰 Tails 7.5 Updates Tor Browser to 15.0.7 and Improves Thunderbird Security Tails 7.5, a privacy-focused Linux distro, upgrades Tor Browser to 15.0.7, updates the Tor client to 0.4.9.5, and improves Thunderbird security. 🔗 Source: https://linuxiac.com/tails-7-5-privacy-focused-linux-distro-released/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #18561 · 24.04.2026 г., 17:47

📰 Canonical finally gives Launchpad (a bit of) a glow-up Launchpad, the home of Ubuntu development, has finally received some design attention. Canonical last updated the site’s homepage back in 2024, but many of the pages that the distro’s developers actually use or reference on a regular basis have remained untouched for the best part of a decade. Now that’s starting to change. 🔗 Source: https://www.omgubuntu.co.uk/2026/04/ubuntu-launchpad-website-revamp #distro#ubuntu

Linuxgram 🐧

@linuxgram · Post #18514 · 21.04.2026 г., 17:38

📰 Ubuntu confirms the 26.10 codename, and it sounds strange… Ubuntu has announced the codename for Ubuntu 26.10 is… “Stonking Stingray”. As codenames go it’s certainly unique. The distro gives each release a codename has an alliterative pairing of adjective and animal, the latter of which becomes the release mascot. The tradition dates back to the first Ubuntu release in 2004 (dubbed ‘Warty Warthog’). Ubuntu 26. 🔗 Source: https://www.omgubuntu.co.uk/2026/04/ubuntu-26-10-codename-confirmed #distro#ubuntu

ПретходнаСтраница 1 од 3Следна