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

Резултати

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

Пребарај: #earn

当前筛选 #earn清除筛选
Crypto Drop Club

@drop_cryptogo · Post #1651 · 10.02.2025 г., 15:15

🗣#Earn Rewards in the Sahara Testnet Sahara is backed by top funds with a $43M investment. What to do: ✔️ Go to here and connect wallet ✔️ Claim free test tokens ✔️ Choose an avatar & complete tasks ✔️ React to "Legend" in community-bible on Discord ✔️ Finish Galxe quests 🟠 Guaranteed rewards via Shards 🟠 Deadline: TBA 🟠 No costs – free to join! Big-name investors, so this one is worth grinding! ☝️ Start trading on Bybit Crypto Drop Club 👉 SUBSCRIBE

Hashtags

CyberCharge Announcements

@cyberchargeannouncements · Post #291 · 26.02.2025 г., 08:51

📢Excited to partner with the Hong Kong Blockchain Association (HKBA) to drive innovation in the #Web3 space! 🤝 CyberCharge, the Web3 & DePIN charging solution that lets you #earn while you power up💰! 🚀@HKBAclub is a key player in Hong Kong’s blockchain scene.Exciting things ahead! ⚡ 🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube

Hashtags

The Ultimate Bombie Strategy!💣 🔥Ready to DOMINATE the #Earn$Bombie mission and grab those TON rewards like never before? If you’re serious about leveling up fast and stacking those $Bombie coins 🪙, follow the ultimate strategy guide to crush the competition and max out your rewards! 💥 🔫1. PRIORITIZE HIGH-DAMAGE BUILDS Upgrade your gear smart! Here’s how you become an unstoppable force on the battlefield: • Critical Hit Bonuses: Always focus on weapons with critical damage potential. Speed and agility are your key to victory. • Stay Agile: Keep moving, dodge often, and strike fast. Speed kills! 🏆2. MASTER THE ARENA LIKE A CHAMPION The Arena is where champions are made — don’t just fight hard, fight smart: • Target Weaker Enemies: Start by targeting lower-level opponents to secure easy wins. • Revenge Mode: Use the bottom-left corner to find enemies who beat you and strike back for revenge! 🎁3. AIRDROP BOX MASTERY — YOUR KEY TO SUCCESS Here’s how you maximize your loot from AirDrop boxes: • Open More Boxes: Always be on the lookout for more AirDrop boxes to score rare items. • Boost Your Level: Increasing your AirDrop level unlocks better, rarer items — get those boosters! ⚙️4. OPTIMIZE YOUR AIRDROP SETTINGS Don’t waste time with manual box openings — automate your success: • Activate Auto-Opening: Enable automatic box openings in settings to save time and maximize efficiency. • Multiple Box Openings: Based on your level, open several boxes at once. I’m currently opening 3 boxes simultaneously! ⭐️5. GO VIP FOR THE EDGE VIP status is a game-changer if you want to stay ahead of the competition: • Faster Rewards: Unlock and open AirDrop boxes quicker with VIP, plus get extra perks for your investment. • More Loot, Less Time: Speed up your gameplay and get more rewards without the grind. 🪙6. MAXIMIZE WITH THE CATIZEN AIRDROP PASS Once you hit Level 60, the game shifts to a whole new level of rewards: • Buy 50 Stars Daily: With the Catizen AirDrop Pass, buy 50 stars daily, unlocking a box with 300 XP. • Level 60 Bonus: At Level 60, the last box repeats daily, earning you steady rewards —between 1500 and 12,000 Bombies every day! ✋7. INVITE FRIENDS FOR EXTRA BONUSES Teamwork makes the dream work! • Extra $Bombie & Boxes: Every time you invite a friend, you both earn extra $Bombie and bonus boxes. • More Friends = More Rewards: The more friends you invite, the bigger your Bombie empire grows! 💰8. SMART INVESTMENTS = BIG REWARDS Want to level up faster? Investing wisely gives you an edge! • Invest What You Can: Only spend what you can afford, but investing in the game can fast-track your progress. • Unlock Better Gear: With small investments, you can unlock stronger items and rewards faster! Let's try to reach the top as fast as possible with the guide and get huge #airdrop! Kill Zombies, Earn $Bombie!🪙

GOLD FOREX SIGNALS [free]™️

@goldfx_free · Post #48693 · 08.11.2025 г., 16:26

KEEP YOUR INVESTMENT COMING TEAM Give me your details to process your registration in our Automated trading system Bot Name Country Resident Email and receiving wallet address for your profits #INVEST AND #EARN💵💵

Hashtags

GOLD FOREX SIGNALS [free]™️

@goldfx_free · Post #48611 · 07.11.2025 г., 18:51

ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ ￴￴￴￴ᅠ Thank You For Your Wonderful Feedback And Congratulations On Your Profit Withdrawal #INVEST#EARN

Hashtags

123•••10•••20•••30•••40•••4849
ПретходнаСтраница 1 од 49Следна