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

Резултати

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

Пребарај: #keepbuilding

当前筛选 #keepbuilding清除筛选
TokenPocket

@tokenpocket_channel · Post #1182 · 05.02.2024 г., 04:25

💥We've reached 500K+ followers! [@​TokenPocket_TP](https://twitter.com/TokenPocket_TP) 💙Thank you for always standing with us and for all the support from [#TPFam](https://twitter.com/hashtag/TPFam)! 💙Enjoy your [#TokenPocket](https://twitter.com/hashtag/TokenPocket) wallet! 👉https://www.tokenpocket.pro/ 👉https://extension.tokenpocket.pro/ [#Keepbuilding](https://twitter.com/hashtag/Keepbuilding) [#TokenPocket](https://twitter.com/hashtag/TokenPocket) 【Details】https://twitter.com/TokenPocket_TP/status/1754359919900340255 【Powered By】Crypto Box

UXLINK

@uxlink_community · Post #420 · 12.04.2025 г., 02:14

Let us focus on what really matters and fundamentals—our ecosystem has leveled up to a new dimension in 2025 Q1. 🚀 - 50 million+ global users, solidifying our position as Web3 social’s leader. 🌍👥 - 5 million+ users on LINE 📱 - 1.2 million+ activated accounts on our OAOG protocol 🌐 - 110,000+ $UXLINK holders—surpassing even USDC. 💰💎 - 400+ partners. Our AI Growth Agent is driving growth for Web3 projects, while FujiPay and FujiCard are set to launch in the first half of this year. 🤝🚀 - Tens of million USD profits: Our business model has achieved PMF (Product-Market-Fit), with rapid growth in revenue & profits. 📊💼 As the largest #Web3 social platform and infrastructure, we will remain transparent in our governance, united in our mission, and focused on social growth and keeping $UXLINK empowered. ✨ This journey is ours to build together. While milestones matter, our vision is the destination—and we’re just getting started. 🚀🤝#UXLINK#Keepbuilding

BNBet

@bnbetofficial · Post #5 · 10.10.2025 г., 09:27

$BNBet Whitepaper is out now 🔥 We’re building a fully onchain Betting market on BNB, simple, transparent, and for everyone. Would love your feedback 👇 Read it here: https://bnbet.gitbook.io/whitepaper #BNBChain#BNBet#KeepBuilding

UXLINK

@uxlink_community · Post #291 · 24.02.2025 г., 02:50

🫡The highly - anticipated 2nd round #UXLINK eco - airdrop is approaching! As a token of gratitude to our dedicated $UXLINK stakers, we are thrilled to announce that we will be distributing 9 listed tokens, namely: $SOLV, $SONIC, $DUCK, $MOZ, $DYOR, $XOXO, $N3, $OBT, and $PINGO. This #airdrop is made possible through the invaluable support of our UXLINK ecosystem partners and @UFLY_Labs. Let's join hands and build UXLINK One Chain together, continuously enhancing the value of $UXLINK! 🚀 For tokens on the Arbitrum network, they will be directly airdropped to the eligible wallet addresses. As for tokens on other blockchains, we will open a claim portal this week for eligible $UXLINK stakers to claim their rewards. Detail rules will be shared later, please stay tuned. UXLINK is bringing high - quality and highly - engaged social user growth to #Web3 projects through the UXLINK Social Growth Layer. #KEEPbuilding✊

UXLINK

@uxlink_community · Post #404 · 09.04.2025 г., 05:48

Tough times? #UXLINK is crushing it—delivering STRONG GROWTH and SOLID PROFITS in Q1 2025! 💪 Our ecosystem’s unstoppable: user base booming, profits soaring, all while keeping the community front and center. Our ecosystem is ALL about GROWTH—serving both end users with seamless adoption & business-end projects with killer infra, tools, and traffic. As long as the industry booms, the hunger for growth STAYS! We’re already making 10+ millions net profit, and expect to achieve 20-30 millions in 2025 - growing strong, reinvesting hard, and riding a positive loop! 💰 With #PayFi , next-level AI tools, and more in the works, profits are about to SKYROCKET! 🚀 We’re relentless—pushing R&D and innovation to be THE go-to for industry growth! #Web3#KeepBuilding

UXLINK

@uxlink_community · Post #450 · 24.04.2025 г., 02:06

🎉 300K+ NEW USERS IN JUST DAYS! 🚀 Thanks to the TikTok fam 🎵—your energy diving into #Web3 is BLOWING OUR MINDS! 🔥 300,000+ creators & users already chose #UXLINK as their Web3 gateway 🌐… and we’re just getting started! 🌟 Our mission? To build the ULTIMATE community bridge—where social growth meets decentralized magic. 🤝💫 Now the question is: WHEN WILL WE HIT 1M? 🤔⏰ Tag a friend who needs to join the revolution 👇 Let’s make Web3 mainstream TOGETHER! 🌍✨ https://ai.happyfair.io/tiktokTask #keepbuilding#CommunityPower#UXLINK

UXLINK

@uxlink_community · Post #295 · 26.02.2025 г., 04:47

UXLINK AI Growth Agent is live!🔥 The First ever AI Agent for Users Growth in the #Web3 world, another big step for Social Growth Layer! What is UXLINK AI Growth Agent: ✅The First AI Agent for Users Growth: powered by @deepseek_ai V3 ✅Cost Reduction and efficiency: Automated repetitive tasks & unleash team's creativity and time ✅Growth Loop: Build a sustainable social media ecosystem, from operations to incentives Only need 3 steps to build an intelligent operation system: 1⃣Simple setup, Fast Deployment 2⃣ AI-Driven Automation 3⃣From Operations to Growth: AI Builds a Growth Flywheel We will offer 30 days free trial period for #UXLINK ecosystem partners to appreciate their support of empowering $UXLINK🚀#AI#DeepSeek#KeepBuilding

UXLINK

@uxlink_community · Post #395 · 07.04.2025 г., 01:22

🚀 BREAKING: $UXLINK hits 1.285M HOLDERS on-chain! 🌐 That’s more than USDC on @arbitrum – a testament to community strength! 💎 Why this matters: ✅ Largest decentralized community ✅ UXLINK ecosystem growing 30% MoM ✅ Keep empowering $UXLINK 🙏 Thank you, global holders! We’re doubling down on innovation – stay tuned for the next chapter. #Web3#CommunityFirst#UXLINK#KeepBuilding

UXLINK

@uxlink_community · Post #399 · 08.04.2025 г., 02:15

💥 UXLINK OAOG PROTOCOL HITS A MILESTONE! Over 1,160,000 accounts activated & 12,000,000 $UXLINK deposited as universal gas! 🌐✨ 🔧 What’s OAOG? Part of #UXLINKOneChain, it’s your KEY to seamless #Web3 access: 🔗 Chain + Account Abstraction = 1 social account + 1 Gas fee for ALL blockchains ✅ No more switching wallets or worrying about different gas token! 🎮 Do it all: Airdrops, DeFi, DEX trades—effortlessly. 🌍 The Future of Web3 is Here Just like Web2 social logins, tens of millions will use OAOG to explore Web3 without barriers. 🌐→💫 We’re building the SUPERGATEWAY to decentralized life—where one account connects it all.🔥 #uxlink#community#KeepBuilding

UXLINK

@uxlink_community · Post #445 · 22.04.2025 г., 05:19

🚀#UXLINK AI Growth Agent IS NOW LIVE ON #TIKTOK! 📈 Meet the ultimate tool for TikTok creators: boost your account growth smarter, faster—and turn followers into web3 pioneers, all in one flow. 🌐✨ As the leading social infrastructure for web3, we’re building the bridge where social success meets decentralized innovation. Why? Because we know: social is the gateway to onboarding millions into #Web3. Ready to level up your TikTok game and shape the future of digital connection? 👇 Dive into the beta today and be part of the movement that’s merging social growth with web3 magic. https://ai.happyfair.io/tiktokTask Let’s turn followers into believers. 🌍💫 #TikToker#KeepBuilding#UXLINK