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

Резултати

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

Пребарај: #coffeeceremony

当前筛选 #coffeeceremony清除筛选

☕ **ETHIOPIA: WHERE COFFEE BECAME SACRED** 🇪🇹 *The Ancient Ritual That Gave Birth to a $15 Billion Industry* In Ethiopia's highlands, where coffee was discovered 1,200 years ago, the traditional coffee ceremony remains unchanged. This sacred 3-hour ritual transforms green beans into liquid gold through patience and community. **The Sacred Process:** 🌿 Hand-picked beans from ancient forests 🔥 Roasted over charcoal in clay pans 💨 Aromatic frankincense purifies the space 🏺 Traditional jebena pot brews perfection 👥 Three rounds: Abol, Tona, Baraka (blessing) **Economic Impact:** • Ethiopian coffee exports: $1.2B annually • Premium beans: $45-65 per pound • Coffee tourism: $50-150 per ceremony In Ethiopia, coffee isn't just a drink - it's a sacred bond between earth and soul. #EthiopianCoffee#CoffeeCeremony#CoffeeOrigin

ancient history of oromoo

@etbisahusen · Post #2119 · 25.09.2025 г., 17:45

Buna Qalaa: More Than Just Coffee ☕️ Did you know the Oromo homeland is the birthplace of Arabica coffee? For the Oromo people, coffee (Buna) is not just a drink; it's a sacred ceremony that binds families and communities. The Buna Qalaa is a cherished ritual of hospitality and respect. The air fills with the sweet aroma of roasting beans, incense (ittana), and lively conversation. It's a slow, beautiful process where every step is deliberate and full of meaning. To be invited to a coffee ceremony is to be welcomed into the heart of an Oromo home. It’s a moment to share stories, blessings, and build connections. It is a true taste of Oromo hospitality! #Buna#CoffeeCeremony#OromoCulture#Hospitality#Community#Ethiopia#Africa http://T.me/etbisahusen

✈️ ETHIOPIAN AIRLINES: AFRICA'S AVIATION CHAMPION የኢትዮጵያ አየር መንገድ፡ የአፍሪካ የአየር ትራንስፖርት ጀግና Not just an airline - an EXPERIENCE at 35,000 feet! 🌍☕ ከአየር መንገድ በላይ - በ 35,000 ጫማ ላይ ልምድ! ━━━━━━━━━━━━━━━━ 🏆 AFRICA'S UNDISPUTED AVIATION HUB 🌍 THE NETWORK: • 130+ destinations across 5 continents • Africa's largest airline network • Addis Ababa = The Gateway to Africa • Direct flights: NYC, London, Beijing, Mumbai, São Paulo • "We connect civilizations!" ━━━━━━━━━━━━━━━━ 🇷🇺 ETHIOPIA ↔ RUSSIA: BRIDGE BETWEEN CIVILIZATIONS ኢትዮጵያ ↔ ሩሲያ፡ የስልጣኔዎች ድልድይ ЭФИОПИЯ ↔ РОССИЯ: МОСТ МЕЖДУ ЦИВИЛИЗАЦИЯМИ ✈️MOSCOW (SVO): 3-4 flights/week | ~7 hours | от $450 ✈️SAINT PETERSBURG (LED): Seasonal flights ለሩሲያውያን ጎብኝዎች: ✅ Visa on arrival (30 days!) ✅ Russian meals available ✅ Gateway to all East Africa ✅ Cheaper than via Dubai/Istanbul "От Москвы до Аддис-Абебы за 7 часов!" ❄️→☀️ ━━━━━━━━━━━━━━━━ ✈️ FLEET OF THE FUTURE: • 140+ modern aircraft (Boeing 787, Airbus A350) • Average age: 7 years (younger than most!) • First African airline with Dreamliner • Full Wi-Fi on international flights ━━━━━━━━━━━━━━━━ ☕ THE EXPERIENCE YOU'VE NEVER HAD 💎 ETHIOPIAN COFFEE CEREMONY AT 35,000 FEET! Imagine: You wake up from comfortable sleep... ✨ Open your eyes... 👀 And there she is - beautiful Ethiopian flight attendant in traditional habesha dress 👰 With jebena (ጀበና) filled with freshly brewed coffee ☕ She performs the ancient coffee ceremony... in the sky! 🌤️ THIS IS NOT A DREAM. THIS IS ETHIOPIAN AIRLINES.🔥 ይህ ህልም አይደለም። ይህ የኢትዮጵያ አየር መንገድ ነው። Only on Ethiopian Airlines: ✅ Traditional coffee ceremony on long-haul flights ✅ Fresh Ethiopian coffee (birthplace of coffee!) ✅ Served by crew in traditional attire ✅ The aroma of home at 35,000 feet ━━━━━━━━━━━━━━━━ 👰 BEAUTY & PROFESSIONALISM Ethiopian cabin crew - recognized worldwide: • Traditional habesha kemis with embroidery • Warm Ethiopian hospitality (የኢትዮጵያ እንግዳ መስተንግዶ) • Multilingual service • "Our crew welcomes you home" ━━━━━━━━━━━━━━━━ 💺 CLOUD NINE BUSINESS CLASS • Lie-flat seats (180° recline) • Ethiopian-inspired design • Authentic cuisine (injera, doro wat in the sky!) • Premium amenity kits • 1000+ entertainment options ━━━━━━━━━━━━━━━━ 💰 SMART PRICES Real examples: • Addis ↔ London: from $450 • Addis ↔ New York: from $650 • Addis ↔ Johannesburg: from $280 ShebaMiles: Earn miles on Star Alliance, upgrade to business, lounge access! ━━━━━━━━━━━━━━━━ 🌟 WHY WE LEAD AFRICA ✅ 4-star Skytrax (highest in Africa) ✅ "Best Airline in Africa" 2023 ✅ Star Alliance member ✅ Ethiopian-owned and operated (Africa's pride! 🇪🇹) ✅ 77+ years of excellence (since 1946!) "የአፍሪካ ኩራት በሰማይ" (Africa's pride in the sky) ━━━━━━━━━━━━━━━━ ✈️ FUN FACTS: 🤯 Only profitable airline in Africa for decades 🤯 Coffee ceremony by popular passenger demand! 🤯 Boeing 787 burns 20% less fuel (eco-friendly!) 🤯 Addis hub: 2,355m altitude - flight starts high! 🏔️ ━━━━━━━━━━━━━━━━ 📱 BOOK NOW: ethiopianairlines.com | 24/7 support | Digital boarding Pro tip: Book direct for best prices + full ShebaMiles! ━━━━━━━━━━━━━━━━ 🇪🇹 MORE THAN AVIATION 🌍 Connecting Africa to the world 💪 African excellence ☕ Ethiopian culture in the skies 🎓 Training Africa's next pilots "When you fly Ethiopian, you fly with Africa's best." ከኢትዮጵያ ጋር ስትበር፣ ከአፍሪካ ምርጥ ጋር ነው። ━━━━━━━━━━━━━━━━ Ready to experience aviation the Ethiopian way? ✈️☕ ━━━━━━━━━━━━━━━━ 🌍 ETHIOPIA | ЭФИОПИЯ | ኢትዮጵያ 📱 Join us: @ethiopia telegram #EthiopianAirlines#FlyEthiopian#AfricanAviation#CoffeeCeremony#AddisAbaba#EthiopianHospitality#Boeing787