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

Резултати

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

Пребарај: #blockdengue

当前筛选 #blockdengue清除筛选
NEA Singapore

@NEASingapore · Post #1168 · 14.11.2025 г., 01:02

This mosquito thought it had found the perfect breeding grounds to raise an army… but every step was BLOCKed 🚫🦟 🔴 𝗕reak up hardened soil 🔴 𝗟ift and empty flowerpot plates 🔴 𝗢verturn pails and wipe their rims 🔴 𝗖hange water in vases 🔴 𝗞eep roof gutters clear and place BTI insecticide Let’s #BLOCKDengue together 👉go.gov.sg/dengue-checklist

Hashtags

NEA Singapore

@NEASingapore · Post #979 · 27.01.2025 г., 02:40

Doing your last round of spring cleaning before the Lunar New Year? Don’t forget to remove all stagnant water. Let’s bring in good health and fortune, not mosquitoes. 🚫🦟 Check out more dengue prevention tips at go.gov.sg/dengue-checklist#BLOCKdengue

Hashtags

NEA Singapore

@NEASingapore · Post #902 · 24.09.2024 г., 09:50

Dengue and Zika, transmitted by Aedes mosquitoes, can cause serious health issues. Although rare, Zika virus infection can cause microcephaly in unborn babies of pregnant women. #BLOCKdengue and Zika weekly. Protect yourself with "S-A-W": go.gov.sg/dengue-zika

Hashtags

NEA Singapore

@NEASingapore · Post #591 · 15.07.2023 г., 02:01

Out of sight, out of mind? Make sure you don’t leave your home’s roof gutters unattended. If it gets clogged with fallen leaves, the accumulated water may become the perfect breeding ground for Aedes mosquitoes. So, make sure to keep your roof gutters clear and place BTI insecticide. Let’s continue to B-L-O-C-K dengue and Zika at least once a week. ✅ Break up hardened soil ✅ Lift and empty flowerpot plates ✅ Overturn pails and wipe their rims ✅ Change water in vases ✅ Keep roof gutters clear and place BTI insecticide Part of the ASEAN Dengue Day series to raise awareness on dengue prevention, check out our earlier posts too! #BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #587 · 09.07.2023 г., 01:00

Love keeping flowers around to brighten up your home? Don’t forget to change the water in flower vases every other day, so that they don’t become mosquito breeding habitats. Let’s continue to B-L-O-C-K dengue and Zika at least once a week. ✅ Break up hardened soil ✅ Lift and empty flowerpot plates ✅ Overturn pails and wipe their rims ✅ Change water in vases ✅ Keep roof gutters clear and place BTI insecticide #BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #578 · 02.07.2023 г., 01:30

Pretty sure that your pails are free from stagnated water? But you’ll never know when water might drip and accumulate. Overturn pails and wipe their rims to be doubly sure! Let’s continue to B-L-O-C-K dengue and Zika at least once a week. ✅ Break up hardened soil ✅ Lift and empty flowerpot plates ✅ Overturn pails and wipe their rims ✅ Change water in vases ✅ Keep roof gutters clear and place BTI insecticide #BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #574 · 23.06.2023 г., 00:30

Excess water accumulated in flowerpot plates is the perfect breeding ground for the Aedes mosquitoes. So, don’t forget to lift and empty flowerpot plates every other day. Let’s continue to B-L-O-C-K dengue and Zika at least once a week. ✅ Break up hardened soil ✅ Lift and empty flowerpot plates ✅ Overturn pails and wipe their rims ✅ Change water in vases ✅ Keep roof gutters clear and place BTI insecticide #BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #566 · 15.06.2023 г., 00:00

It’s ASEAN Dengue Day! Observed every 15 Jun, it raises awareness on ways to prevent dengue. Let’s continue to B-L-O-C-K dengue and Zika at least once a week. Learn more about dengue prevention here: go.gov.sg/mozzieproof#BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #528 · 25.03.2023 г., 06:51

‘Little but lethal’, the small female Aedes aegypti mosquito transmits the Dengue virus that can be deadly. Launched today, NEA’s National Dengue Prevention Campaign 2023 aims to rally the community to take immediate action to reduce the continued high number of dengue cases. All of us need to do our part to #BLOCKdengue, and those residing in dengue cluster areas should carry out the ‘S-A-W’ actions to protect themselves and their loved ones. More at https://go.gov.sg/dengue-campaign-launch-mar2023

Hashtags

NEA Singapore

@NEASingapore · Post #355 · 20.05.2022 г., 02:44

⚠️ Dengue alert! Set up alerts on the myENV app to find out if the places you live and work in, or frequent for leisure activities, have a higher dengue risk. #BLOCKDengue

Hashtags

NEA Singapore

@NEASingapore · Post #590 · 14.07.2023 г., 00:29

#SGDengueUpdate 235 new dengue cases and 44 active dengue clusters were reported in the week ending 8 Jul 2023. No new Zika cases were reported. Let’s continue to actively #BLOCKDengue: https://go.gov.sg/mozzieproof

123•••67
ПретходнаСтраница 1 од 7Следна