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

Резултати

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

Пребарај: #prediction

当前筛选 #prediction清除筛选
Red Nile

@rednile12 · Post #10626 · 05.01.2026 г., 20:40

🚨Just a reminder: On November 17, 2025, in RedNile Episode 62, I predicted the U.S. regime change play in Venezuela. The U.S. operation we're seeing now—including the shocking January 3rd move against Maduro—was foreshadowed in this analysis I published a month ago. 🎞This video breaks down the entire blueprint: 🔹 The historical imperial script from Monroe to Trump 🔹 How the "War on Drugs" is used as cover 🔹 The sanctions, coups, and media narratives targeting Venezuela 🔹 The real geopolitical goal: stopping Latin America's shift toward multipolarity Everything you need to understand the why, who, and what behind today's events is explained here. 📺 Watch the full analysis from November 2025: https://youtu.be/Lt_gFn8Dxj8?si=VTMvyRfVfR77OYp_ --- 💠 Follow: Telegram | Twitter | YouTube | TikTok: @rednile12 #Venezuela#RegimeChange#Prediction#Geopolitics#USIntervention

EdgeMarket.AI 📣

@edgemarketai · Post #8104 · 16.04.2026 г., 09:51

Will Manchester City win the Premier League 2025/26 title This is now live on EdgeMarket Not hype not opinions Structured prediction driven by signal and validation Enter the market Submit your position Track the outcome Deadline May 24 Join here ⬇️ https://edgemarket.ai/bnb/football/will-manchester-city-win-the-premier-league-202526-title/statistics/69df3ecf93819e68721b57cd #EdgeMarket#PremierLeague#Prediction#FootballMarkets

EdgeMarket.AI 📣

@edgemarketai · Post #8082 · 28.03.2026 г., 11:40

📊 MARKET QUESTION LIVE Will the Toronto Maple Leafs win their first April 2026 playoff game? This isn’t about takes it’s about probability. On EdgeMarket: → AI models track performance signals → Market sentiment is verified → Data updates in real time Watch how the probability moves as we approach playoffs. This is live predictive intelligence. #EdgeMarket#NHL#SportsData#AI#Prediction

Venture Village Wall 🦄

@venturevillagewall · Post #4281 · 01.03.2025 г., 22:00

Bitcoin Predicted to Reach $200K Soon Standard Chartered's Geoff Kendrick forecasts Bitcoin will hit $200K this year and could reach $500K before Trump exits the presidency. Predictions reflect growing confidence in BTC's potential growth trajectory. #Bitcoin#Crypto#Finance#Investment#Prediction#Market#Trump#StandardChartered#DigitalAssets#GeoffKendrick

EdgeMarket.AI 📣

@edgemarketai · Post #8036 · 12.03.2026 г., 12:04

New high-volatility geopolitical question live ⚠️ Will a senior political leader become the target of an assassination attempt? Markets react before media confirms. AI tracks signal shifts in real time. Watch sentiment move. #Geopolitics#Prediction#MiddleEast#AIModels#Forecasting#RiskSignals#EdgeMarket

Venture Village Wall 🦄

@venturevillagewall · Post #4266 · 28.02.2025 г., 07:00

AI Predictions: From Vacuums to Real Impact AI-powered prediction platforms are gaining traction, with a focus on forecasting reactions based on content and audience. Initial predictions using tools like ChatGPT yield 17% accuracy, but considering audience interactions can boost accuracy to 83%. This innovative approach helped a startup refine its pitch to enter Y Combinator. Discover more insights on enhancing prediction accuracy in various fields here. #AI#Startup#Prediction#YCombinator#Marketing#Innovation#Tech#Growth#Entrepreneurship#Forecasting#AudienceAnalysis#DataScience#MachineLearning#Success#Business#Trends#Platforms#Metrics#Investment#VC

Venture Village Wall 🦄

@venturevillagewall · Post #4260 · 27.02.2025 г., 13:00

Latest Funding Rounds for Startups Recent funding rounds: - Flanks raised $14.70M on Feb 26, 2025. Focus on wealth management and core business growth. Read more - Infimind secured $13.77M on Feb 25, 2025. Enhancing e-commerce with AIGC technology. Read more - Anagram raised $10M on Feb 26, 2025. Human-driven security platform. Read more - Ignota Labs received $6.90M on Feb 26, 2025. Focused on toxicity prediction. Read more - HouseWhisper acquired $6.70M on Feb 25, 2025. AI for real estate professionals. Read more - Afynia Laboratories raised $5M on Feb 25, 2025. Read more - Dispersa received $4.07M on Feb 25, 2025. Read more - Swirepay raised $3.40M on Feb 25, 2025. Customizable B2B SaaS for transactions. Read more - CQR secured $3M on Feb 26, 2025. Read more - Vidyut received $2.50M on Feb 26, 2025. Read more #Fundraising#Flanks#Infimind#Anagram#Ignota#HouseWhisper#Afynia#Dispersa#Swirepay#CQR#Vidyut#AI#Tech#Startups#Finance#Ecommerce#Security#SaaS#B2B#Prediction#VC