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

Резултати

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

Пребарај: #deals

当前筛选 #deals清除筛选
Desi Memes Funny Jokes

@DESI_MEMES_Funny_Jokes · Post #7089 · 01.05.2025 г., 17:05

Great Summer Sales from tomorrow!! Join now and get notified to exciting and jaw-dropping #deals and #loots🔥 https://t.me/+tNuUiQLlNNIzZGFl https://t.me/+tNuUiQLlNNIzZGFl

Hashtags

BLC Market - mini-app BulCoin

@bulcoin_blc · Post #299 · 13.03.2026 г., 10:00

How the deal will be conducted in BLC Market We continue to showcase the interface of the upcoming BLC Market app. Today — how the deal between the client and the contractor will take place. When the client selects a contractor, a deal is created within the platform. The process looks like this: • the client creates a deal • funds are blocked within the platform • the contractor performs the work • after confirmation, the result is transferred to the client • funds are transferred to the contractor Such a system allows to protect both parties of the deal and reduce the risk of fraud. All calculations within the platform will be conducted using BLC without commission, or with the token chosen by the user, for a commission - which will go to the BLC liquidity pool. In the following posts we will show: • how the arbitration system works • what happens if a dispute arises • how users can protect their interests Early access to interface testing is granted to Pioneers participants. #tasks#freelance#deals

BLC Market - mini-app BulCoin

@bulcoin_blc · Post #294 · 10.03.2026 г., 10:00

How the task search will work in BLC Market We continue to demonstrate the interface of the future BLC Market application. Today - how users will be able to find tasks and performers. The application will have a convenient search, where you can: • view available tasks • filter by categories • search by keywords • choose tasks by budget Each task will have a card with a description, price, and completion time. Performers will be able to quickly find suitable tasks and send their proposals to customers. This creates a full-fledged service market where customers and performers can interact directly. In the following posts, we will show: • how a deal is made within the platform • how deal protection works • how crypto-arbitrage will be arranged Early access to interface testing is given to Pioneers participants. #tasks#freelance#deals FAQ | BUY

纯情男高

@hanzichen · Post #706 · 11.05.2025 г., 17:13

AppSumo A platform that offers lifetime deals on software and digital tools for entrepreneurs, developers, and small businesses. AppSumo helps you discover new and useful apps at heavily discounted prices — often one-time payments instead of recurring subscriptions. 🔗 Links: - Website - Softwares - YouTube - Blog ❗️Friendly reminder: If you find it useful, You may star the repo/app, donate to the developer, or perhaps you may also contribute to the development of this project. 🏷 Tags: #Website#Deals#LifetimeDeals

Desi Memes Funny Jokes

@DESI_MEMES_Funny_Jokes · Post #5423 · 11.10.2024 г., 12:28

🌟EAR BUDS @ ₹39🌟 🔥LOOT DEAL OF THE DAY🔥 🛍Grab fast before it gets Out of stock. Get similar deals in future by joiningLoot Indian Deals🛍 🔰Note- Check all deals instantly 🔰 #Loots#Indian#Deals#offers

App Store Deals

@appstoredeals · Post #739 · 23.05.2024 г., 11:13

FREE GAME❗💥 🔹 Anti Pong is now free for a limited time❗ (was $0.99) ✨ Avoid The Ball! ❌ ENDEDhttps://apple.co/3wCZ667 💬great twist on a classic game. enjoy local multiplayer and smooth dark mode. highly recommended! ⚡️Boost🔸@AppStoreDeals#apple#deals#free#apps

Daily Channels

@dailychannels · Post #6760 · 20.03.2026 г., 13:00

Channel: Amazon.com USA Deals Members: ~3.15K 💢 Username: @dealsunlimitedusa Description: Great selection of the best Amazon.com deals every day! 🏷 Tags: #shop #amazon#amazon.com #shopping#sales#deals https://lve.to/4glrsiawix

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40064 · 11.11.2025 г., 06:01

Singles’ Day ✨🛍️ November 11 (11.11) — the date’s four "1"s symbolize single life. What began in the 1990s as a playful “anti-Valentine’s” celebration in China has grown into one of the largest shopping days in the world! @googlefactss [Read more] #SinglesDay #1111 #SelfCare#ShopSmart#Deals#November11#FunFacts#History

Trump and Mirziyoyev exchanged compliments in New York, discussed multi-billion dollar deals, and extended invitations for further cooperation (meeting video analysis). https://yep.uz/en/2025/09/trump-mirziyoyev-compliments-deals-samarkand/ #trump#mirziyoyev#uzbekistan#samarkand#deals#nyc#un#news#cooperation