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

Резултати

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

Пребарај: #celebrities

当前筛选 #celebrities清除筛选
Kursiv Uzbekistan (Eng)

@kursivuzeng · Post #2674 · 27.02.2026 г., 06:53

🌟 TIME Unveils 2026 Women of the Year List 👩 TIME has named 16 influential women from entertainment, sports, business and activism as its 2026 Women of the Year, celebrating their contributions to equality and social progress. 🎬 Honourees include actor-singer Teyana Taylor, Lucy Liu, Sheryl Lee Ralph, filmmaker Chloé Zhao, musician Brandi Carlile, and Olympic champion Sydney McLaughlin-Levrone. Authors, activists, and business leaders such as Mel Robbins, Mariska Hargitay, Amy Sherald, Reshma Kewalramani, Kecia Steelman, and Reshma Saujani are also featured. Humanitarian figures like Isata Dumbuya, Sister Norma Pimentel, Safeena Husain, and Mahnoor Omer are recognised for their grassroots impact. Read more on the website #Celebrities

Hashtags

Bali News

@balinews · Post #310 · 03.02.2025 г., 11:06

🎤 Usher feels happy in Bali 😎 R'n'B singer Usher visited Bali and called himself the happiest man in the world. 📱 In one of his latest posts, the rapper shared his joy of being in Bali and said he was enchanted by the island of gods. 👏 Subscribers supported him in high appreciation of the island and its beauties. @BaliNews #celebrities

Hashtags

Bali News

@balinews · Post #54 · 21.05.2024 г., 09:30

✈️Elon Musk flew to Bali for the first time to launch Starlink Photos of the founder Elon Musk in a traditional Balinese shirt and frangipani necklace have already traveled around the world. On the day of his arrival, he had time to participate with the country's President Joko Widodo in the opening of the World Water Forum and admire the nature of Bali. I'm amazed by the mangrove trees and this huge amount of greenery around, it's really cool. shared the Tesla founder did what he came for – he tested the Starlink internet service. @BaliNews #celebrities

Hashtags

Bali News

@balinews · Post #49 · 16.05.2024 г., 11:05

😮Elon Musk flies to Bali to unveil Starlink service SpaceX founder Elon Musk will be in Indonesia for the launch of the company's Starlink internet satellite service in the country on May 19. This was announced by the Minister for Investment, Mr. Luhut. The event is expected to take place alongside President Joko Widodo on the sidelines of the World Water Forum, which kicks off on the island on Saturday, May 18. Since the beginning of the year, the heads of two of the world's biggest technology companies have already visited Indonesia, promising major investments in the country. They are Apple CEO Tim Cook and his Microsoft counterpart Satya Nadella. @BaliNews #celebrities#events

Bali News

@balinews · Post #549 · 09.01.2026 г., 09:35

⭐️It looks like a movie featuring Gerard Butler may be filming in Ubud 📸 The actor has been spotted several times in the city center, calmly walking around, chatting with people, and taking photos with fans — without security or a film crew, dressed in casual everyday clothes, far from the usual Hollywood glamour. 👍 The very fact that a Hollywood star of this level can freely walk around Ubud and interact with locals has once again fueled conversations about Bali as a place where celebrities can be “just people,” rather than targets for paparazzi. What do you think — is this a film shoot, or is Butler simply vacationing on the island? #celebrities#Ubud@BaliNews

12
ПретходнаСтраница 1 од 2Следна