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

Резултати

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

Пребарај: #bgb

当前筛选 #bgb清除筛选
UXLINK

@uxlink_community · Post #194 · 15.01.2025 г., 10:17

We are thrilled to announce that certain unlocked tokens from the excellent projects invested by UFLY Labs will be shared to UXLINK Season 2 stakers. We share values with community, as promised, as always. The co-promotion and empowerment between UFLY Labs and #UXLINK ecosystems have given UFLY Labs an extraordinary start in 2025! We must learn from the industry leaders #BNB#BGB#GT and benefit $UXLINK holders. No doubt that a strong and lasting community is the only shortcut to make the UFLY evergreen. Keep building!🫡

🚀Bitget Wallet Contest Week has begun! The project team has prepared many events for us with prizes in $TRUMP, #USDT, $BGB and KeyShards tokens. All week from January 20 to January 26, complete tasks to receive drops from participant projects🌟 Launch 💙Bitget Wallet Lite directly in Telegram to get these incredible prizes! 🎉 #Trump#BGB#BitgetWallet

💙Bitget Wallet Launches a New Era of Web3 Payments Bitget Wallet has announced its 2025 strategy, focusing on the concept of #PayFi. This is a real breakthrough in the world of crypto payments, which turns passive Web3 investments into an active financial instrument for everyday use. 📊Integration of earnings, expenses and transfers With over 60 million users worldwide, Bitget Wallet is redefining the role of cryptocurrency in personal finance. The PayFi system allows users to earn, spend, and send cryptocurrency in a single ecosystem, making it as useful as possible in everyday life. ✈️PayFi Flywheel Model The strategy is based on the PayFi Flywheel model, which transforms the traditional crypto wallet from a simple storage tool into a full-fledged financial hub. Users will be able to deposit assets, such as stablecoins, into savings accounts with real income, which are immediately used to cover daily expenses under the concept of “buy now, pay later.” 💳Launch of Bitget Wallet Card Key new products include the Bitget Wallet crypto card, which is supported by 💳Mastercard. This card will be linked to a multi-currency, crypto-friendly international bank account, greatly expanding the possibilities for using your crypto assets in real life. In addition to the card, users will have access to an in-app section for online shopping thanks to partnerships with companies like #Bitrefill, #IvendPay and #Coinpal. 🗺Supporting growing markets The significant growth in users in Africa, the Middle East and Latin America (over 1000% in 2024) highlights Bitget Wallet's commitment to making cryptocurrency accessible to everyone, especially those who have been left out of the traditional banking system. Alvin Kahn, COO of Bitget Wallet: This is not just a product — it is a movement that will make cryptocurrency a viable financial instrument for billions of people. We integrate blockchain technology into everyday life, creating a new paradigm for personal finance. 💰How to leverage it? It is assumed that settlements will be made through $BGB, the holders of which will become the beneficiaries of the new direction of the exchange. If you use Bitget Wallet Lite to collect KeyShards, which will probably also be converted to $BGB — you can easily migrate to Bitget Wallet by importing a seed phrase or private key and get all the benefits of PayFi Flywheel. #BitgetWallet#Web3#DeFi#BGB

Data | CryptoAttack 🎅🏼

@cryptoarsenal · Post #62693 · 11.04.2026 г., 20:57

📆 🍒Основные события предстоящей недели Понедельник 13 апреля: 🔁#STRKОбновление Starknet 🔁#TRB Обновление Tellor ⌚️#BLEND Токенсейл BLEND ✏️#INK Ink запустит систему поинтов 👍#NOX NONOS выпустит 0xNOX 😎#UMBRA Umbra начнет тестирование приватных ончейн-переводов 🇺🇸 Existing Home Sales (Mar) - 17:00 мск Вторник 14 апреля: 🔓 Разлоки: Pieverse (#PIEVERSE) - 1,50% (7,73 млн $) 🔁#GNO Обновление Gnosis 👍#AGI Delysium запустит Lucy Skills Marketplace 🇷🇺 Начало Blockchain Forum 2026 в Москве 🇺🇸 PPI (MoM) (Mar) - 15:30 мск Среда 15 апреля: 🔁#ATOMОбновление Cosmos Hub 👍#DBT TGE DBT ⌚️#USDP Дедлайн Parallel USDp для миграции MIMO в PRL 🇷🇺 Завершение Blockchain Forum 2026 в Москве 🇺🇸 Crude Oil Inventories - 17:30 мск Четверг 16 апреля: 🔓 Разлоки: Arbitrum (#ARB) - 0,94% (10,80 млн $) - STBL (#STBL) - 4,17% (15,41 млн $) 🔁#XLM Обновление Stellar 🎮#TLM Alien Worlds запустит открытую альфа-версию Alien Legends Academy 🇺🇸#RENDER Начало RenderCon 2026 в Лос-Анджелесе 🇺🇸 Philadelphia Fed Manufacturing Index (Apr) - 15:30 мск - Initial Jobless Claims - 15:30 мск Пятница 17 апреля: 🔓 Разлоки: DeBridge (#DBR) - 6,34% (9,47 млн $) - Aster (#ASTER) - 0,98% (52,46 млн $) 🍿#REAL Real Token объявит о стратегическом сотрудничестве 🇺🇸#RENDER Завершение RenderCon 2026 в Лос-Анджелесе Суббота 18 апреля: 👍#BGB Bitget запустит платформу IPO Prime Воскресенье 19 апреля: 🔓 Разлоки: Yooldo (#ESPORTS) - 3,32% (19,01 млн $) #Calendar#CAreportCAbot