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

Пребарај: #nasdaq100

当前筛选 #nasdaq100清除筛选
NEWS 鏈新聞-ABMedia

@abmedia_news · Post #24345 · 04.05.2026 г., 11:01

【💰 交易市場|為搶進 SpaceX、OpenAI 與 Anthropic IPO 熱潮,那斯達克與標普放寬標準】 #SpaceX#OpenAI#Nasdaq100 標普與那斯達克 5 月修改規則,縮短 SpaceX 等巨頭入選指數的等待期。 那斯達克增設快軌機制,市值前 40 名企業掛牌 15 天即可空降成為成分股。市場擔憂被動資金過早湧入,導致股價在定價前遭到嚴重扭曲。 📍閱讀全文: https://abmedia.io/nasdaq-sp500-listing-rules-relaxed 📍 訂閱鏈新聞頻道:https://linktr.ee/abmedia.io

Crypto M - Crypto News

@CryptoM · Post #65223 · 12.04.2026 г., 04:14

🚀 Sky Co-Founder Rune Faces Losses in Leveraged Oil and S&P 500 Positions Sky co-founder Rune's leveraged positions have recently experienced significant losses. According to Odaily, data from Hyperbot indicates that Rune's sevenfold leveraged short position on the Nasdaq 100 was closed 16 hours ago. Currently, he holds long positions valued at approximately $518,000, including a 20-fold leveraged long position in WTI crude oil futures and a sevenfold leveraged position in Brent oil. Additionally, Rune maintains a 20-fold leveraged short position on the S&P 500, valued at $159,000. At present, all of Rune's positions are in a loss state, with the total value dropping to around $678,000, reflecting a floating loss of approximately $61,000 and an investment return rate of -22.68%. Rune initially entered these positions last month when oil prices were rising, achieving a floating profit exceeding $1 million. However, recent fluctuations and declines in oil prices have turned these positions from profit to loss. #Sky#Rune#LeveragedTrading#OilFutures#SP500#Nasdaq100#FinancialLoss#WTICrude#BrentOil#Investing#SKY

Crypto M - Crypto News

@CryptoM · Post #64545 · 09.04.2026 г., 07:14

🚀 Whale Adjusts Investment Strategy Across Major Markets On April 9, a significant investor, known for substantial positions in three major markets, closed all long positions in WTICRUDE and BRENTOIL, according to BlockBeats. Previously, the combined holdings in these oils exceeded $14.1 million, resulting in a loss of over $3.9 million upon closure. Following this, the investor opened a short position in WTICRUDE at an average price of $92.3, with a current scale of $9.3 million and a liquidation price of $117.6. This adjustment has led to the following main positions across the three markets: In U.S. stocks, the investor holds long positions in the Nasdaq 100 and S&P 500, with a scale of $38.1 million and an unrealized profit of $430,000. In the cryptocurrency market, the investor maintains a long position in Bitcoin, with a scale of $12.05 million at an average price of $6,540, resulting in an unrealized profit of $30,000. In commodities, the investor's short position in WTI crude oil stands at $9.3 million, with an unrealized loss of $290,000. The address associated with these transactions is 0x8af700ba841f30e0a3fcb0ee4c4a9d223e1efa05. #Investment#MarketStrategy#WTICrude#BrentOil#USStocks#Nasdaq100#SP500#Bitcoin#Cryptocurrency#Commodities#Trading#Blockchain#BlockBeats#BTC

PRICE ACTION EXPERT

@priceactionexpert · Post #7905 · 23.11.2024 г., 08:14

https://x.com/priceactiongann/status/1830819785975955483 #nifty#geometry#banknifty New Course Book! ✅Market movements through the lens of advanced Geometric concepts. ✅Multidimensional and Spherical Time concepts of Trading with our upcoming course (book), ✅This innovative book dives deep into the concept of time-related trading, blending advanced geometric principles with practical markets Exploring Triangles, Squares, and Circles. ❤️🙏❤️ #stocks#stockmarket#gann#trading#time#gold#silver#xauusd#SPX500#DowJones#NASDAQ100

PRICE ACTION EXPERT

@priceactionexpert · Post #7723 · 03.09.2024 г., 04:08

https://x.com/priceactiongann/status/1830819785975955483 #nifty#geometry#banknifty New Course Book! ✅Market movements through the lens of advanced Geometric concepts. ✅Multidimensional and Spherical Time concepts of Trading with our upcoming course (book), ✅This innovative book dives deep into the concept of time-related trading, blending advanced geometric principles with practical markets Exploring Triangles, Squares, and Circles. ❤️🙏❤️ #stocks#stockmarket#gann#trading#time#gold#silver#xauusd#SPX500#DowJones#NASDAQ100