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

Резултати

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

Пребарај: #grace

当前筛选 #grace清除筛选
Pensive|

@PensivePost · Post #5008 · 19.03.2021 г., 16:31

And as you fall and shatter. Darling, think of the glory of your rise. Think of the potential that lies. You must gather all that lay scattered. First on your knees and then finally, you stand on your feet. #poetry#review#grace

Pensive|

@PensivePost · Post #4853 · 01.02.2021 г., 03:16

On this day I conclude my body and blend in God to discover all those whom I'd once lost! I tasted every bit; every risk. Blessings were showered abundantly; every moment was a gift! I cherish the smiles that came into existence because of my presence. But now, my body has perished. So don't you cry O My Beloved! For I'll always be there, in times of your happiness even in times of despair! I happily dive in my Creator and bid adieu to His beautiful creations! #review#grace#poetry

Pensive|

@PensivePost · Post #4838 · 28.01.2021 г., 09:36

So rich and rare. You hold me up and blend me in your air. I scent your breath, your body! I make you go insane about your own-self because I make you smell like a wild rose with gold petals! You bring me close and I spread kisses all over your body. I peck your wrist, you inhale me unnoticed! You are privileged to own me, to keep me a secret, for I am too precious to reveal and too exotic to be concealed. I'll be one of those perfume bottles you'd love to keep even after there's nothing left of me! #grace#poetry#review

Pensive|

@PensivePost · Post #4829 · 26.01.2021 г., 16:51

I seek motivation from within.. I hold the will to try until my goal is fulfilled...!! Afterall, my despair got some faithful hope and a chance to try once more.... When I look into the mirror, I just don't see a person burdened with numerous reasons to fall for sadness but an absolutely distinct soul crawling around the space alone to fetch happiness in its own universe. Just like the moon is scarred with craters but still gentle with its coldness, so is my universe scratched with shooting stars but holds galaxies of unbearable positive energy vibing with my soul! #review#poetry#grace

Pensive|

@PensivePost · Post #4874 · 05.02.2021 г., 09:21

LILIES AND ROSE I rushed to the store and bought a bouquet of lilies and a red rose. I was like an enthusiastic guitar, gleeful; cheerful and indeed, grateful. I decorated the house with fairy lights and the rooms with crimson ribbons and balloons. I smile through the memories as how on our first Valentine's Day I proposed her with a ring of platinum and bouquet of lilies! Lilies are her favourite and so are mine! I love my babe, I love her pleasant smile! I remember brushing her cheeks with white lilies and did I tell you that her name too, is Lily! Must be wondering why I bought a red rose!? Let me tell you as I drive along. An hour ago, Lily gave birth to a baby girl, who owns that velvet rose and happiness of many more! Perfect. I reached in time. There's my family. Mom, dad, in-laws. Numerous smiles; blooming happiness. The moment, I wish I could pause! I push the door and see my lifelines; my queen and my princess! "Papa's here with lovely lilies and Wow, a crimson rose! ", she says as I kiss her forehead and hand her the bouquet I bore. I look at my precious child. Her daddy-like features and mom-like skin pinkish white! The rose adorns my angel as I rest her in my arms. I gently peck her little fingers and pray, "let there be more love in the world my lord, for I'm blessed with so much; what more can I want! " #ballad#review#grace

🆕Книжный сервис «Строки» Новинки ММКЯ-2024 Аня Бергман «Ведьмы с Вардё» Дизайн — Анастасия #Николаева Мэдди Доусон «Магия найденный вещей» Дизайн — Луиза #Ромазанова Кристин Миллер «Семь правил несерьезных отношений» Дизайн — Глеб #Назаров Юлия Симбирская «Феликс Булкин» Дизайн — Сергей #Гаврилов Энн Лян «Надеюсь, ты это прочтешь» Дизайн — Avva #Grace Клаудия Кэррол «Алгоритм любви» Дизайн — Елена #Новожилова Ваньянь Лу «Плакальщица» Дизайн — #huaepiphany. Оливия Хоррокс «Прекрасные маленькие глупышки» Дизайн — Ксения #Спижевая. Кристин Кайоль «Любовь, что медленно становится тобой» Дизайн — Алина #Анисимова Елена Минкина-Тайчер «Там, где течет молоко и мед» Дизайн — Виктория #Лебедева 📖@nabookov 🏃Марафон новинок ММКЯ-2024 💝 Дарим 9 клевых романов