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 слични објави

Пребарај: #selfcustody

当前筛选 #selfcustody清除筛选
Crypto M - Crypto News

@CryptoM · Post #65103 · 11.04.2026 г., 01:36

🚀 Exodus Launches Self-Custody Payments App for Bitcoin and Stablecoins Exodus has introduced a new self-custody payments application, enabling users to spend Bitcoin and dollar stablecoins. According to NS3.AI, the app is compatible with merchants that accept Visa and Apple Pay, providing a seamless payment experience for cryptocurrency holders. #Exodus#Bitcoin#Stablecoins#SelfCustody#CryptoPayments#Visa#ApplePay#Cryptocurrency#BTC

Crypto M - Crypto News

@CryptoM · Post #65102 · 11.04.2026 г., 01:25

🚀 Exodus Introduces New Payment Feature for Select States Exodus, a publicly listed cryptocurrency wallet provider, has launched a new feature called Exodus Pay. According to Foresight News, this feature aims to transform its self-custody storage application into a tool for everyday payments. Currently, the service is available only to users in five states, including New York and California. #Exodus#PaymentFeature#ExodusPay#Cryptocurrency#SelfCustody#EverydayPayments#NewYork#California#ForesightNews

Crypto M - Crypto News

@CryptoM · Post #65248 · 12.04.2026 г., 09:35

🚀 Tether CEO Advocates for Open AI Development Tether CEO Paolo Ardoino has expressed his views on the development of artificial intelligence, stating that AI should be as open as freedom. According to Odaily, Ardoino criticized the centralized approach to AI development, describing it as a 'dead end.' In contrast to the closed AI systems being developed by major tech companies, Tether is exploring alternative methods through QVAC, which focuses on running AI models on local devices. This approach aims to give users control over their data and computing power, aligning with the crypto industry's core principle of self-custody, where users maintain autonomy over their data and computational resources. #Tether#CEO#AIdevelopment#openAI#freedom#centralizedAI#selfcustody#crypto#localdevices#dataprivacy

Crypto M - Crypto News

@CryptoM · Post #65024 · 10.04.2026 г., 14:21

🚀 France Advocates for Enhanced Crypto Regulations Amid MiCA Concerns French authorities are advocating for stricter cryptocurrency regulations, focusing on stablecoins issued by non-European entities. According to NS3.AI, a Bank of France official, Denis Beau, has called for tighter limits under the Markets in Crypto-Assets (MiCA) framework, specifically targeting non-euro stablecoin payments. Beau expressed concerns that the current MiCA rules only partially mitigate risks associated with the widespread adoption of these stablecoins. In addition, France's National Assembly has adopted a provision requiring self-custody reporting for cryptocurrency holdings exceeding a 5,000 euro threshold. However, this measure has not yet completed the legislative process, indicating ongoing discussions and potential adjustments before final implementation. The move reflects France's proactive stance in addressing regulatory challenges posed by the evolving crypto landscape. #France#crypto#regulations#stablecoins#MiCA#BankofFrance#DenisBeau#NationalAssembly#cryptocurrency#selfcustody#legislation

Venture Village Wall 🦄

@venturevillagewall · Post #4279 · 01.03.2025 г., 16:00

Swiss Central Bank Rejects Bitcoin Reserves Swiss National Bank President Martin Schlegel dismisses holding bitcoin as reserves, citing volatility and security issues. He emphasizes that cryptocurrencies don’t meet the necessary characteristics of a good currency. Read more Amidst market turbulence, Bitcoin saw a sharp decline, hitting an intraday low of $78,197 and trading below $80,000 at $79,875. BTC is down 7% today and 21.9% over the past month. Liquidations in derivatives reached $955.12 million, with significant amounts linked to bullish BTC and ETH positions. Market experts indicate the current downturn is less severe than previous crises, suggesting a healthy release of market risks. Kentucky passes a bill unanimously protecting Bitcoin Rights and self-custody, marking a significant legislative move for cryptocurrencies. #Bitcoin#Crypto#Finance#LazarusGroup#Ethereum#MarketTrends#Regulation#Volatility#Investing#Kentucky#BitcoinRights#SelfCustody#Trading#Liquidations#US#Banks#Macroeconomic#Arbitrage#MarketAnalysis#FTX#CryptoNews