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

Пребарај: #earlyaccess

当前筛选 #earlyaccess清除筛选

На просторах интернета наткнулся на китайский стартап Dora AI. Пишешь промпт — и вуаля: анимация таблиц, инфографика, визуализация карт, симуляция чатов и куча всего. Выглядит круто, но что-то слишком уж гладко и просто. Не тянет ли на очередной развод с «ИИ»? Чувствую, за ширмой тысяча индусов пашут. 😅 Были же прецеденты: 1. Builder.ai (оценка $1,5 млрд) обещал кодить софт и упростить разработку программного обеспечения до уровня "заказа пиццы", а на деле 700 человек вручную работали, обманув Microsoft и Amazon на $500 млн. 2. Kaedim хвастался 3D-моделями от ИИ, но их лепили люди из Аргентины и Индонезии за $1–4. Dora AI — реальный ИИ или очередной фокус? Можно зарегаться на ранний доступ через Discord #earlyaccess#ainews | AcidCrunch

DeckForge Announcement

@deckforge_official · Post #328 · 22.08.2025 г., 14:50

🔥 20,000+ Runs and Counting — You’re Forging Legends! Forgers, you’re absolutely unstoppable🚀 Together, you’ve already completed over 20,000 runs — and the numbers keep climbing. That’s 20,000+ battles fought and strategies tested. You’re not just playing — you’re shaping the future of DeckForge with every move. ⭐️ As a thank you: We’re sending a wave of Stars to the most active players. Check your wallets — you’ve earned it. 🎁 More rewards are coming! ➡️DeckForge - Play Now! We see your clips, your insane combos, your feedback. We see you. And we’re grateful. Stay fierce. Stay forged. #DeckForge#ClosedBeta#EarlyAccess Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements👉DeckForge

DeckForge Announcement

@deckforge_official · Post #315 · 23.07.2025 г., 10:28

From the Forge #11: 🔨 | Closed Beta Is Forged Our Adventure Map is ready to welcome the first wave of players — every node, every choice, every twist now set in place. Meanwhile, our Art Team is hard at work bringing new Jokers and Bonus Cards to life — adding layers of depth and crazy combos to your future decks. We’re also preparing a special challenge for our early players — with rewards waiting for those brave enough to take the first steps. The Closed Beta is just days away. Get ready — the Forge is heating up 🔥 #DeckForge#ClosedBeta#EarlyAccess Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements👉DeckForge

DeckForge Announcement

@deckforge_official · Post #312 · 17.07.2025 г., 11:36

From the Forge #10: 🔨 | UI Overhaul & Art Expansion Big things are happening behind the scenes Over the past weeks, our team has been reworking the UI of DeckForge — and it’s now smoother, sharper, and far more enjoyable to navigate. The updated interface is already integrated into the latest Closed Beta build. But we’re not stopping there. Our ARTists are hard at work expanding the visual universe of DeckForge — refining old elements, creating new ones, and pushing the style to the next level. We're feeling incredibly optimistic as we finalize the build for our earliest players. Soon, you'll step into the experience and help us shape the game’s future. Your feedback is our forge. Together, we’re getting closer to Open Beta — one step at a time. Stay forged 🔥 #DeckForge#ClosedBeta#EarlyAccess Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements👉DeckForge

DeckForge Announcement

@deckforge_official · Post #232 · 02.05.2025 г., 13:00

Why Early Matters We’re still early. Which means you’re not just joining a game — you’re getting in before the noise. 🔵 Early players will enter Closed Beta before the public launch. 🔵 You’ll get access to exclusive rewards and collectibles — not available later. 🔵 You’ll help shape the game through feedback, testing, and community votes. 🔵 You’ll build reputation and status before the seasonal competition begins. 🔵 Your progress and impact will carry forward into the full release. Now’s the time to get in early. Join the Discord. Get the role. Be part of the first wave. #DeckForge#EarlyAccess#ClosedBeta Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements

Airdrop3 LTD

@airdrop3ltd · Post #445 · 17.02.2024 г., 09:00

Omchain DID Early Access now! Earn 100 Points to unlock OMC Coin! 🔥🔥 🔥 Secure your Omchain Profile today! 🔥 https://did.omchain.io/?referrer=97187422 Connect your Metamask or mobile wallet, sign in, provide your email, and confirm via email. Invite friends for even more rewards! Stay tuned for exciting updates. Don't miss out on this limited opportunity! Act now and be part of the Omchain revolution! ✨ #Cryptocurrency#Blockchain#OMCCoin#EarlyAccess

🎙NEW PROJECT 30-100X🔥🔥🔥 🤌 CROSS THE AGES🚀🚀 💫 This is your opportunity to be among the first to experience the #crosstheagesgame and #Metaverse💫 Join this #giveway complete tasks and become apart of something monumental 🤯 Join now🧨 👉https://gleam.io/drnAT/the-cross-the-ages-nft-giveaway👈 #earlyaccess

DeckForge Announcement

@deckforge_official · Post #231 · 30.04.2025 г., 12:02

🎮 DeckForge Discord is LIVE. The gates to the Forge are finally open — and you can be among the first to enter. 👑 Early players will receive the Pioneers role — a special early access badge that will unlock exclusive rewards and the future Founder Pack. Here's how to claim your role: 1. Join the DeckForge Discord server. 2. Check out the rules and verify yourself. 3. Go to the #claim thread and get the Pioneers role. 💰 Pioneers role = early access to the Beta, unique rewards, and hidden advantages before the global launch. The earlier you forge your legacy, the greater your rewards. See you inside. 🔗DeckForge Discord #DeckForge#EarlyAccess#FoundersPack Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements