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

Резултати

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

Пребарај: #proton

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

@linuxgram · Post #18608 · 28.04.2026 г., 22:27

📰 Proton Experimental and Proton 11 Beta updated to fix issues with the EA App Valve released a small tweak update to both Proton Experimental and the Proton 11 Beta, bringing in an update to help with the EA App.Read the full article on GamingOnLinux. 🔗 Source: https://www.gamingonlinux.com/2026/04/proton-experimental-and-proton-11-beta-updated-to-fix-issues-with-the-ea-app/ #proton

Hashtags

sudo recast

@sudo_recast · Post #341 · 11.07.2022 г., 17:47

#Proton Down - https://twitter.com/search?q=protonmail%20down&src=typed_query&f=live - https://twitter.com/ProtonSupport/status/1546545761512464385 - https://protonstatus.com/incidents/195

Hashtags

sudo recast

@sudo_recast · Post #337 · 09.07.2022 г., 12:41

> If you have been inactive on #Proton Mail for one year (12 months) or more, access to your account and all data associated with it may be removed. https://proton.me/support/inactive-accounts

Hashtags

Linuxgram 🐧

@linuxgram · Post #18715 · 08.05.2026 г., 21:21

📰 Proton Experimental gets fixes for Rocket League, Crimson Desert, Helldivers 2 and more Valve just launched the latest exciting upgrade for Proton Experimental, to ensure as many Windows games as possible run well on Linux / SteamOS machines.Read the full article on GamingOnLinux. 🔗 Source: https://www.gamingonlinux.com/2026/05/proton-experimental-gets-fixes-for-rocket-league-crimson-desert-helldivers-2-and-more/ #linux#proton

Linuxgram 🐧

@linuxgram · Post #18688 · 06.05.2026 г., 13:24

📰 VKD3D-Proton 3.0.1 Brings More Improvements For Direct3D 12 On Vulkan Hans-Kristian Arntzen of Valve's Linux graphics driver team announced the release today of VKD3D-Proton 3.0.1 for Direct3D 12 over the Vulkan API... 🔗 Source: https://www.phoronix.com/news/VKD3D-Proton-3.0.1 #linux#proton

Linuxgram 🐧

@linuxgram · Post #18623 · 30.04.2026 г., 08:40

📰Proton Experimental updated to get Crimson Desert working again on Linux / SteamOS A recent update to Crimson Desert has been causing problems on Linux / SteamOS with it not launching, so Valve patched Proton Experimental to fix it.Read the full article on GamingOnLinux. 🔗 Source: https://www.gamingonlinux.com/2026/04/proton-experimental-updated-to-get-crimson-desert-working-again-on-linux-steamos/ #linux#proton

Linuxgram 🐧

@linuxgram · Post #18518 · 21.04.2026 г., 21:04

📰 Proton Experimental upgraded to Proton 11 for better Linux gaming compatibility After releasing the big Proton 11 Beta to run more Windows games on Linux / SteamOS, Valve just upgraded Proton Experimental some more too.Read the full article on GamingOnLinux. 🔗 Source: https://www.gamingonlinux.com/2026/04/proton-experimental-upgraded-to-proton-11-for-better-linux-gaming-compatibility/ #linux#proton

Linuxgram 🐧

@linuxgram · Post #18580 · 27.04.2026 г., 08:04

📰D7VK v1.8 Continues Improving Legacy Direct3D Atop The Vulkan API D7VK as what began as an implementation of the Direct3D 7 API on top of the Vulkan API, based off DXVK as part of Steam Play (Proton) for D3D8 through D3D11 support, continues enhancing its legacy D3D API support that over time has stretched now from D3D7 to D3D3... 🔗 Source: https://www.phoronix.com/news/D7VK-1.8-Released #proton#steam

Linuxgram 🐧

@linuxgram · Post #18654 · 02.05.2026 г., 16:30

📰 Steam On Linux In April Pulled Back From Its Record High Marketshare Steam on Linux use in March had skyrocketed to 5.33%, a 3.1% boost month-over-month and easily the highest level we've seen Steam on Linux at since its inception more than a decade ago. This record growth came amid the ongoing success of the Steam Deck handheld and Steam Play (Proton) for enabling more Windows games to run well on Linux. The April numbers are in and the Linux gaming marketshare pulled back somewhat but still remaining healthy... 🔗 Source: https://www.phoronix.com/news/Steam-April-2026-Survey #linux#proton#steam

sudo recast

@sudo_recast · Post #260 · 05.06.2022 г., 19:59

#ProtonMail 啓用新的品牌名 #Proton 統一多項服務,意在構建隱私生態 https://www.wired.com/story/proton-mail-calendar-drive-vpn/ https://proton.me/news/updated-proton 新的設計風格相當輕浮。 #design

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