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

Резултати

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

Пребарај: #dca

当前筛选 #dca清除筛选
Host Testing and evaluation

@HostEvaluate · Post #871 · 13.08.2023 г., 12:21

#crunchbits#DCA Host Provider: crunchbits Location: Liberty Lake, Washington, USA Specification: 2vCore (E5-2696 v4) | 3GB RAM | 25GB SSD | 4TB @ 250Mbps | $11.69 / Yearly (Promo code: PATIENCE) 性能上来讲,能用。IP 已不能解锁 Netflix 但仍然算比较干净。现在以 he 为主不像以前基本走 WSI. https://pastebin.com/L2Ja8XjS 流媒体报告 https://pastebin.com/dmMVgQ8r

SLEX NEWS

@slex_io · Post #87 · 08.09.2023 г., 13:34

🎉Check out DCA Strategy page on SLEX🎉 🌈Hey, SLEXians, do you know something about one of the most influential and profitable investment and trading strategies — Dollar-Cost Averaging (DCA)? 📊 DCA investment strategy is: ✅Minimum Risk; ✅ Maximum Returns; ✅ Simplifying Decision-Making. 📚We've prepared the whole page on the SLEX platform to ensure you have comprehensive guides, real-life examples, and pro tips for trading successfully!🎯 📈 Explore DCA — this is Your Path to Profitable Trading on SLEX👉slex.io/dca #SLEX#DCA#CryptoTrading#ProfitableInvesting Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

Артур Хуснуллин | Блог

@husnullinartur · Post #643 · 04.03.2025 г., 09:38

🔥 Батя в крипте – доллар косит 🔥 Сидим мы тут, братцы, в баньке, парок гоняем, пивком запиваем… И вот зашел разговор: а что, если бы ты, как умный, пять лет назад по соточке баксов в Биток закидывал каждый месяц? 🤔 Ну, считай сам: всего-то вложил 6 000 баксов. Мелочь, а приятно. А сейчас бы на балансе уже 16 657 баксов красовалось! Х2.7 на ровном месте! 🔥 Вот это я понимаю – тема! 🔥 Пацаны, пока кто-то ноет, что рынок скачет, другие просто стабильно кидают бабки и не парятся. DCA – это как отложенный жирок перед зимой, только в битке. 📊 График есть – всё по красоте! 💡 Вывод: Хочешь, чтобы через 5 лет в бане ты уже не просто пивко пил, а вискарь наливал? Просто инвестируй регулярно! 🚀 #Крипта#ПацанскийИнвест#ДелаемБабки#DCA#Bitcoin

Crypto M - Crypto News

@CryptoM · Post #64661 · 09.04.2026 г., 13:04

🚀 Bitcoin's Current Volatility May Present a Generational Buying Opportunity Cryptocurrency analyst Ali Martinez recently shared an analysis on the X platform, suggesting that instead of debating whether Bitcoin has hit its bottom, attention should be focused on whether the current volatility presents a 'generational buying opportunity.' According to Odaily, Martinez identifies key 'value zones' for the current cycle based on long-term trend lines, on-chain liquidity, and cost distribution indicators. The UTXO Realized Price Distribution (URPD) indicates a significant concentration of holdings between $63,111 and $70,685, forming the primary support band. If Bitcoin falls below $63,111, the market may enter a liquidity vacuum. From a long-term perspective, Bitcoin is nearing a critical ascending trend line from the past decade, approximately between $56,000 and $60,000. Historically, this position has often marked the accumulation phase before significant price increases. In more extreme scenarios, the CVDD indicator suggests a structural bottom around $47,960, while the MVRV 0.8 range at approximately $43,647 indicates a market in an 'extreme pain' phase, typically associated with exhaustion of selling pressure. In the event of a black swan event, prices could briefly dip to an extreme range of around $36,657. Based on these zones, Martinez employs a dollar-cost averaging (DCA) strategy, gradually increasing positions across different support bands to reduce overall holding costs. He believes the market is currently in a phase of low sentiment, but potential opportunities are gradually emerging. #Bitcoin#Cryptocurrency#CryptoTrading#MarketAnalysis#Volatility#InvestmentOpportunity#DCA#OnChainAnalysis#CryptoMarket#TradingStrategy#BTC

Addis Standard

@addisstandardeng · Post #21605 · 04.03.2026 г., 08:32

News: #Ethiopia, #Kenya agree to launch joint military operations to secure border corridor, #LAPSSET Ethiopia and Kenya have agreed to strengthen security coordination along the #Moyale–#Marsabit–#Turkana corridor, endorsing structured joint military operations aimed at addressing cross-border threats and safeguarding key infrastructure linking the two countries. The agreement is part of renewed efforts to operationalise the existing Defence Cooperation Agreement (#DCA) between the two neighbours. Under the arrangement, the Ethiopian National Defence Force (#ENDF) and the Kenya Defence Forces (#KDF) are expected to undertake phased and coordinated operations targeting vulnerable border areas and strategic assets. In a related development, Ethiopia’s defence ministry also held bilateral talks with a delegation from the #Rwanda Defence Force (#RDF) on the margins of the Adwa anniversary celebrations. According to RDF, discussions focused on deepening.... Read more: https://addisstandard.com/?p=55528