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

Резултати

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

Пребарај: #inspirationinvoga

当前筛选 #inspirationinvoga清除筛选
In Voga | Fashion & Web 3.0

@invogafashion · Post #3495 · 24.08.2023 г., 10:19

I present a soft, relaxed, cozy, warm soul (and body 😉) plaid shirt. Autumn is coming 🍂 and we will all need it paired with denim, leather jackets and trench coats soon. And for those who can't wait - try to style with summer cotton skirts, one love 💕 #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3485 · 23.08.2023 г., 09:42

🌺 Flowers always, 🌼 flowers everywhere! 🌺Flower Like: - choker - belt (I liked it very much 👌🏼 - as an alternative to a choker) - brooch 🌸Flower on: - shoes - swimsuit - shirt #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3432 · 25.04.2023 г., 08:13

TOP 5 ideal neighbors for metallic trousers: 1. White T-shirt 2. Black/white tank top 3. Basic jersey 4. Masculine shirt or jacket 5. Classic longsleeve Shine with pleasure and let the whole world be reflected in your pants - no matter how it sounds😂 #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3266 · 04.11.2022 г., 12:55

There are five must-have accessories for the upcoming (and for someone have already come) cold weather: 1. Voluminous long scarf 2. Bib 3. Short or long gloves 4. Puffy/quilted bag 5. Balaclava #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3249 · 18.10.2022 г., 10:32

Let's look at the beauty celebration from Prada about the new fragrance PARADOXE Here we have everything in style: conciseness in color and silhouettes; oversized jackets socks a drop (or not a drop) of glitter and a few feathers leather crossbody with very short straps And triangles, triangles, triangles😊 #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3240 · 14.10.2022 г., 16:49

Hoodie + Coat - Yes or No? As for me, there is nothing better and more convenient than such a couple for daily routine worries that have to be done more often than bright events happen😉🤷🏼‍♀️ While it is still not too cold, the coat can be left open. The hoodie can be worn without an underlayer. However, it is also not forbidden to pry off the turtleneck to save the throat and tighten the belt on the coat. #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3238 · 13.10.2022 г., 16:39

A bit of street style from Paris Fashion Week Spring 2023: - total denim, asymmetric denim, double waist, - loose knit jersey, - bomber jackets, leather coats, and trench coats, - fit and transparency, - balaclavas, - over-the-knee boots and high boots #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3218 · 05.10.2022 г., 08:31

☕️It's cloudy and rainy outside the window☔️. The mood is to wrap yourself in a knitted dress and enjoy your favorite cappuccio - what could be better for a Wednesday morning? Favorite🏆 styles: 1. Knitted dress with sneakers 2. Knitted dress with trumpet/jockey boots that overlap with the dress. 3. Knitted dress overskirt 4. Knitted dress with rough, worn leather #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3179 · 27.09.2022 г., 09:15

I went to Etro Spring 2023 street style for paints, prints, and textures, sharing the mood I caught there and photos made by my own hands 🤲🏼 I’ll start with the atmosphere, the show, and as a result, the street style took place in the industrial zone of Milan and was accompanied by a roar, howl, and signals of disgruntled trucks 🚚🚛 , traffic that was not blocked, but photographers and street stylers scurrying everywhere and everywhere, significantly complicated it 🔴 And then everything is as expected - notes of ethnicity in the form of jersey with fringes, small and complex prints, bright saturated colors, patchwork, some leather, but more suede. I have loved Etro for many years and have chosen the perfect accents for my wardrobe there! ❤️🤎 #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3158 · 21.09.2022 г., 09:53

In the meantime, Milan is taking over the baton of Fashion week, in which I am also going to participate and share with you. We review and study London street style. Lots of ruffles and frills, puffed sleeves and huge collars, brocade and tulle combined with a bit of English stiffness, plaid, lots of Mary Jane variations, golfs, leather, and punk casualness 🎸🤘🏼 #inspirationINVOGA

In Voga | Fashion & Web 3.0

@invogafashion · Post #3091 · 27.08.2022 г., 11:32

Who has butterflies in their stomach? 🦋😉 Release! This summer, and next fall, you can definitely👌🏼 We are not limited to flowers, we add butterflies in all dimensions - tops, jewelry, bags, belts, shoes, and when autumn comes, it will come to jackets. Catch it while the season and treat with care😉 #inspirationINVOGA

123•••10•••1617
ПретходнаСтраница 1 од 17Следна