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

Пребарај: #gumart

当前筛选 #gumart清除筛选
Gumart Announcement 🛒

@gumartec · Post #277 · 07.07.2025 г., 08:27

🌐 Gumart Goes Global: GuGoGlobal Official Recap 🎬 From the streets of Paris to the shores of Cape Town, GuGoGlobal wasn’t just a campaign — it was a movement. 🕯 📌 Campaign Impact: 🌐 5 continents, 20+ cities 👥 100,000+ Gumart residents participated 🎁 $25,000+ in rewards distributed 🚀 Hundreds of check-in videos from real users 🙏 Thank you to every Gumart Resident, partner, and friend around the world who made this campaign unforgettable. Your energy, creativity, and belief in our vision are what bring Web3 to life — city by city, step by step.💸☄️ #GuGoGlobal#Gumart

Gumart Announcement 🛒

@gumartec · Post #280 · 21.07.2025 г., 08:15

🗺Where will you swipe next? 💳GuPay is still live — where will you swipe next? New York, Seoul, Manila, Miami… — We’ve already seen GuCard go global. 🌎 But for us, every payment counts — whether it's coffee near home or a flight across borders 📌 Let's share some moments with us: 1️⃣Use GuCard this week. 2️⃣Snap a photo and post to your X . 3️⃣Use hashtag #Gumart#GuPay Let’s show the world what crypto can actually do.🛒

Gumart Announcement 🛒

@gumartec · Post #181 · 05.01.2025 г., 15:19

✨🥳 GUCARD CREATIVE CONTEST IS HERE! 🥳✨ Are you ready to show off your creativity and love for Gumart? 💸 Join the Gucard Creative Contest and turn your ideas into amazing content! 🎥🖌 👍 How to Join: 1️⃣ Create unique content (video, photo, meme, or text) featuring Gucard or Gumart. 2️⃣ Post it on X or YouTube with the hashtag #Gucard#Gumart 🏆Prizes Await You: 🎖Main Prizes: 1st Place: 1,000 USDT (1 winner) 2nd Place: $500 USDT (3 winners) 3rd Place: $50 USDT (5 winners) 🌟 Community Choice Awards: 50 winners: $10 each (based on community engagement). 💳 Special Bonus: All winners will receive a free Gucard! 🗓Timeline: 🕐 Start: January 5, 2025 ⏳ End: January 19, 2025 🔥 Criteria for Winning: Creativity, quality, and interaction - bring your A-game! #GuMinigame

Gumart Announcement 🛒

@gumartec · Post #276 · 02.07.2025 г., 11:03

‼10,000+ TRANSACTIONS IN 20 DAYS 🤑 GuPay Team Cup – FIFA Club World Cup 2025 is going global - and it’s powered by BNB Chain ⚡️ From Real Madrid to Man City, 32 legendary football clubs are battling it out. But this time, it's not just on the field — it's on-chain. 🏟 📣 Gumart is rewriting what mass adoption looks like: 10,000+ real-world transactions made through GuPay across hotels, stores, and events — all in less than 3 weeks.⬆️ 🚀 Built on BNB Chain's trusted infrastructure, Gumart is leading the charge in making crypto usable, visible, and impactful in everyday life. ➖Want to join? Pick your team and make transactions with GuPay. Help your squad rise to the top. 🌐 Be where culture, payments, and crypto collide. #GuPayTeamCup#Gumart#BNBChain

Gumart Announcement 🛒

@gumartec · Post #244 · 15.04.2025 г., 07:23

🎬 Gumart is in Paris Blockchain Week 2025 🇫🇷 #GuGoGlobal campaign – a journey to take Gumart around the world and bring Web3 adoption closer to real life! 📍 First Stop: Paris Blockchain Week 2025 Our team just landed in Paris, the heart of innovation and fashion, to showcase Gumart at one of the most prestigious Web3 events in the world! From networking with top-tier founders and VCs to sharing the stage with the best builders in the space, Gumart is here to make waves. 🎥👉 Watch the highlight video from our Paris mission – and feel the energy! 💡We’re on a mission to show the world how Gumart is building the future of crypto payments, e-commerce, and DeFi — one region at a time. Real people. Real places. Real utility. 🚀 Next stop? Maybe your city. Don’t blink 👀 Let’s take Web3 mainstream – together 🌐 #GuGoGlobal#Gumart#PBW2025#Web3Adoption#ParisBlockchainWeek#CryptoInRealLife