@mountstorm · Post #692 · 05.08.2023 г., 16:00
Twas the night before finals, And all through the college, The students were praying For the last minute knowledge. #yeah
Hashtags
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
Пребарај: #yeah
@mountstorm · Post #692 · 05.08.2023 г., 16:00
Twas the night before finals, And all through the college, The students were praying For the last minute knowledge. #yeah
Hashtags
@mountstorm · Post #670 · 25.07.2023 г., 07:14
We need to be educated! #yeah
Hashtags
@mountstorm · Post #657 · 18.07.2023 г., 10:34
Always hate comes from below #yeah
Hashtags
@mountstorm · Post #653 · 16.07.2023 г., 04:16
That Eye Blunt Injury The incident of a blunt eye injury during a football game caused me to spend a week alone in the hospital, which led to the discovery of my sense of self. I associate mostly with being a student, as I have always been passionate about learning and developing my knowledge. However, the experience of the injury made me realize that being cautious and aware of my surroundings is also a defining part of my identity. As a student, I am constantly learning and growing, but as someone who has suffered an injury, I am also aware of my vulnerability. This experience has taught me to be more careful and attentive in my day-to-day life, especially when participating in physical activities. Overall, the experience has helped me to redefine my identity and to appreciate the importance of taking care of myself. #yeah
Hashtags
@mountstorm · Post #638 · 08.07.2023 г., 05:23
Today is the last day, last night, last late-night mafia gatherings, last dinner together, last secret friend gift, last team building, and last memorable conversations. #yeah
Hashtags
@mountstorm · Post #630 · 05.07.2023 г., 12:47
🥷 If you can climb the real mountain, why can't you climb your imagined ones? #yeah
Hashtags
@mountstorm · Post #593 · 25.05.2023 г., 10:20
Pain is temporal, remembering valuable ones is rare. #yeah
Hashtags
@mountstorm · Post #259 · 29.06.2022 г., 02:09
#yeah
Hashtags
@mountstorm · Post #203 · 06.06.2022 г., 05:35
😌 5 Exams out of 6, I got from all '5' mark #yeah
Hashtags
@mountstorm · Post #170 · 30.05.2022 г., 08:15
Summer. High School graduates still have the aftertaste of the graduation party and now are preoccupied with summer holidays. While my bro, a 9th grade graduate, can chill for the entire season, he will work on his academic interests and chill. Along with participating in extracurricular summer programs, he will be reading books, however cliche it sounds. Reading a book is like investing in real-estate. As long as you get the right book/estate, you are in a slowly-but-surely growing business. No need for a solid schedule or a measurable goal - how many pages to read daily, specific deadlines - in the beginning. Planning is important, I'd say, when and if there is already a vivid picture of what exactly you need and want to read. I started the process with whatever I had in hand - a fairy-tale collection, a magazine, or a random novel. Bit by bit, it's been getting more clear what genre/author's style is mine and what book to read next. The difference between a "good" book and a "bad" one for me is the first ten pages. Asking for advice on what to read from others is also better done in later stages, I believe. Suggested books are better added to the foundation laid by you. #yeah
Hashtags
@mountstorm · Post #187 · 04.06.2022 г., 18:20
Saturday classes 😬 = Vocab game 😋 Accuracy is fine, bro, calm down) #mountstorm#yeah
Hashtags
@mountstorm · Post #253 · 22.06.2022 г., 09:54
🥳 Finally got a certificate of Basic secondary Education with Honours 9th specialized school. P.s/ бордовый аттестат 😮💨 #oqiganlaga_mazza#yeah
Hashtags