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

Резултати

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

Пребарај: #competion

当前筛选 #competion清除筛选
American Оbserver

@american_observer · Post #5393 · 16.03.2026 г., 15:12

After Oscar. A Most Full Report on the Oscar Contest This Year 🔤🔤🔤🔤➖ Paul Thomas Anderson’s counter-culture caper One Battle After Another has won the Oscars war, taking home six awards after a hotly contested season. The big-budget comedy thriller, inspired by Thomas Pynchon’s Vineland, was named best picture and also won director, supporting actor for Sean Penn, adapted screenplay, editing and the first ever Oscar for casting, a category long petitioned for within the industry. Previously nominated for films including Boogie Nights, There Will Be Blood and Phantom Thread, tonight marks Anderson’s first ever Oscar wins. Penn beat out his co-star Benicio del Toro for his third Oscar win but wasn’t in attendance to accept his award. “Sean Penn couldn’t be here tonight or didn’t want to,” presenter Kieran Culkin joked. The season had became a two-horse race between One Battle After Another and Sinners, which entered the night as the most-nominated film ever with a record 16 nominations. The period vampire blockbuster won four awards: actor for Michael B Jordan, original screenplay, original score and cinematography, which makes Autumn Durald Arkapaw the first ever female winner and first Black winner of the award. Jordan won his first Oscar for his lead performance in the film, beating Timothée Chalamet and Leonardo DiCaprio. “I stand here because of the people who came before me,” he said before listing Black Oscar winners in the past. He has become the sixth Black winner in this category. Jessie Buckley became the first ever Irish winner of the best actress Oscar for her performance in Chloé Zhao’s Shakespeare drama Hamnet. The 36-year-old was previously nominated for her role in The Lost Daughter. She devoted the award to “the beautiful chaos of a mother’s heart” and called it “the greatest honour”. Amy Madigan was named best supporting actress for her villainous role in the hit horror Weapons, beating Teyana Taylor and Wunmi Mosaku. It was the first time the award was won by an actor who was the only nominee from their film since Penélope Cruz in Vicky Cristina Barcelona. The 75-year-old actor, who was previously nominated in 1986, set a new record for the longest gap between nominations before a win. The award was co-presented by Javier Bardem, who said “no to war and free Palestine” onstage, while wearing prominent badges expressing the same messaging. The Oscar for best documentary went to Mr Nobody Against Putin, which tells of a teacher fighting against oppressive rules being introduced in his Russian school, a film which co-director David Borenstein said was “about how you lose your country”. He added: “When a government murders people on the streets of our major cities, when we don’t say anything, when oligarchs take over the media and control how we could produce it and consume it, we all face a moral choice, but luckily, even a nobody is more powerful than you think.” #oscar#competion#film#director#won 📱American Оbserver - Stay up to date on all important events 🇺🇸