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

Резултати

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

Пребарај: #systemd

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

@linuxgram · Post #18227 · 28.03.2026 г., 22:17

📰 KaOS 2026.03 Released With Major Move Away From systemd Components KaOS 2026.03 removes systemd-boot and mkinitcpio, adopts Limine and Dracut, and introduces a new Niri-based desktop environment. 🔗 Source: https://linuxiac.com/kaos-2026-03-released-with-major-move-away-from-systemd-components/ #systemd

Hashtags

Linuxgram 🐧

@linuxgram · Post #18156 · 23.03.2026 г., 16:48

📰Someone Forked Systemd to Strip Out Its Age Verification Support The project removes the birthDate field systemd added last week in response to age verification laws. 🔗 Source: https://feed.itsfoss.com/link/24361/17304579/systemd-fork-strips-out-age-verification #systemd

Hashtags

Linuxgram 🐧

@linuxgram · Post #18134 · 21.03.2026 г., 15:10

📰 SysV Init 3.16 Released With Cleanups, Improved systemd Unit To SysV Script Conversion For any holdouts still running SysV Init instead of systemd or other alternatives like OpenRC, SysV Init 3.16 is out as the first release in a half-year and bringing a few refinements... 🔗 Source: https://www.phoronix.com/news/SysV-Init-3.16 #systemd

Hashtags

Linuxgram 🐧

@linuxgram · Post #17898 · 25.02.2026 г., 22:10

📰 systemd 260-rc1 Released: New "mstack" Feature, System V Service Scripts No Longer Supported The first release candidate of systemd 260 is now available for testing. Systemd 260 finally does away with System V service scripts support. Also notable to systemd 260 is the work around the new "mstack" feature... 🔗 Source: https://www.phoronix.com/news/systemd-260-rc1 #systemd

Hashtags

Libreware

@libreware · Post #1572 · 05.04.2026 г., 19:22

systemd birthDate Merge: Corporate Filings & Governance Failure Investigation pulled Amutable's founding documents from the German Handelsregister The corporate filings show three equal shareholders, no outside investors, and self-dealing exemptions that let any founder sign contracts between the company and their own personal entities All three founders were employed at Microsoft when they signed the founding deed. A hidden shareholders' agreement referenced three times in the Articles of Association but never filed publicly governs economic rights, IP assignment, and vesting terms the public cannot see. Three decisions put the birthDate field into #systemd. Each was made by someone with a direct financial interest in the outcome No one disclosed those interests. systemd has no conflict-of-interest policy, no steering committee, no community veto, and no disclosure requirements. The project that boots every major Linux distribution has less formal governance than a typical mid-size open source project.

Hashtags

Libreware

@libreware · Post #1405 · 08.02.2025 г., 00:45

Lennart Poettering intends to replace "sudo" with #systemd's run0. Here's a quick PoC to demonstrate root permission hijacking by exploiting the fact "systemd-run" (the basis of uid0/run0, the sudo replacer) creates a user owned pty for communication with the new "root" process. This isn't the only bug of course, it's not possible on Linux to read the environment of a root owned process but as systemd creates a service in the system slice, you can query D-BUS and learn sensitive information passed to the process env, such as API keys or other secrets. https://fixupx.com/hackerfantastic/status/1785495587514638559 Nitter mirror: https://xcancel.com/hackerfantastic/status/1785495587514638559

Hashtags

Linuxgram 🐧

@linuxgram · Post #18251 · 31.03.2026 г., 06:54

📰 The One Trick That Made Immutable Linux Easier For Me There's a systemd utility that lets you "inject" tools into a read-only OS at runtime, without rebooting the system. Here's my exploration. 🔗 Source: https://feed.itsfoss.com/link/24361/17309280/systemd-sysext #linux#systemd

Linuxgram 🐧

@linuxgram · Post #18220 · 28.03.2026 г., 11:00

📰 Fish 4.6 Shell Brings Support For Recent systemd Environment Variables Fish 4.6 released today as the newest version of this Rust-based interactive shell for Linux and other platforms... 🔗 Source: https://www.phoronix.com/news/Fish-4.6-Released #systemd#linux

Linuxgram 🐧

@linuxgram · Post #18122 · 20.03.2026 г., 11:14

📰Systemd Introduces Birth Date Support for Upcoming Linux Desktop Age Controls A recent systemd update introduces birth date storage, supporting ongoing efforts to implement age-based access controls in the Linux desktop stack. 🔗 Source: https://linuxiac.com/systemd-introduces-birth-date-support-for-upcoming-linux-desktop-age-controls/ #linux#systemd

Linuxgram 🐧

@linuxgram · Post #17971 · 04.03.2026 г., 19:51

📰 systemd 260-rc2 Released With More Changes Last week marked the release of systemd 260-rc1 with a new "mstack" feature, a new "FANCY_NAME" field for os-release, dropping System V service script support, and other changes. Out today is systemd 260-rc2 release with more changes in further working its way toward a stable release for empowering 2026 Linux distributions... 🔗 Source: https://www.phoronix.com/news/systemd-260-rc2 #systemd#linux

Linuxgram 🐧

@linuxgram · Post #17940 · 02.03.2026 г., 04:16

📰 New to Linux? These 4 systemd Tools Help You Fix Common Issues Stop guessing, start investigating. Here are 4 systemd tools that make Linux troubleshooting easy. 🔗 Source: https://itsfoss.com/systemd-troubleshoot-tools/ #linux#systemd

Linuxgram 🐧

@linuxgram · Post #18192 · 26.03.2026 г., 10:43

📰 Inside the Systemd Age Verification Debate: Developer Responds to Criticism A single pull request turned a quiet open source contributor into the unlikely target of one of the Linux community's most heated controversies. We interacted with Dylan Taylor to hear his side of the story. 🔗 Source: https://feed.itsfoss.com/link/24361/17306445/dylan-taylor-systemd-controversy #systemd#linux#opensource

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