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

Резултати

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

Пребарај: #recycleourewaste

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

@NEASingapore · Post #1170 · 18.11.2025 г., 03:22

Batteries are a big no-no in blue recycling bins as they could short-circuit and set fire to other materials. Drop them off in e-waste recycling bins instead. Learn more: go.gov.sg/e-waste#RecycleOurEWaste

NEA Singapore

@NEASingapore · Post #1153 · 24.10.2025 г., 01:04

Still holding on to your spoilt electrical & electronic devices that are beyond repair? It’s time to let it go! Recycle them to recover precious materials (e.g. gold, silver, copper) that can be used to make new products. Learn more about how to recycle your e-waste at go.gov.sg/e-waste #RecycleOurEWaste#RecycleRight

NEA Singapore

@NEASingapore · Post #1146 · 11.10.2025 г., 01:02

𝗟𝗲𝘁’𝘀 𝗸𝗲𝗲𝗽 𝗲-𝘄𝗮𝘀𝘁𝗲 𝗼𝘂𝘁 𝗼𝗳 𝗼𝘂𝗿 𝗹𝗮𝗻𝗱𝗳𝗶𝗹𝗹𝘀! Here’s how you can make a difference: 1. Fix your device instead of buying a new one 2. Opt for second-hand items 3. Donate working devices to someone who needs them 4. Recycle your e-waste: go.gov.sg/e-waste Join us at the International E-waste Day event to learn more! 🕰️12 Oct 2025 (Sun), 11.30am to 5pm 📍Bedok Town Square Every small action counts towards a greener future. 💚 #RecycleOurEWaste#RecycleRight

NEA Singapore

@NEASingapore · Post #489 · 16.01.2023 г., 10:10

We all wish for abundance during Lunar New Year, so let’s preserve our planet’s precious resources by recycling e-waste properly. 🐰💚♻️ Find out where you can recycle your e-waste here: go.gov.sg/e-waste #RecycleOurEWaste#RecycleRight

NEA Singapore

@NEASingapore · Post #205 · 04.06.2021 г., 02:13

E-waste recycling bins are available from today, at selected Dairy Farm Group & Harvey Norman outlets, ahead of NEA’s national e-waste management scheme on 1 Jul 2021. Drop off your e-waste and earn points that can be redeemed for shopping vouchers. Find out where the bins are at https://go.gov.sg/e-waste #RecycleOurEWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #300 · 04.01.2022 г., 09:30

#DidYouKnow e-waste can have many useful materials, including gold, silver, copper or plastic, that can be recovered and made into new products? Test your knowledge and share your views on e-waste recycling at go.gov.sg/ewaste-survey #RecycleOurEWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #672 · 14.10.2023 г., 01:00

Here’s a #FunFact on International E-waste Day: #DidYouKnow e-waste contains many useful materials, including gold, silver, copper or plastic, that may be recovered and made into new products? ♻️ Let’s #RecycleOurEWaste properly. Visit NEA’s (go.gov.sg/e-waste) and ALBA Singapore’s websites (www.alba-ewaste.sg) for the locations of the e-waste recycling bins and more information about the e-waste management system. #RecycleRight Let’s also reduce the amount of e-waste generated by: (a) considering if you really need to buy a new product, or if the current one can be repaired (b) choosing second-hand products over new products (c) donating devices that are in good condition to those who could put them to better use

NEA Singapore

@NEASingapore · Post #286 · 25.11.2021 г., 02:01

It’s sales galore, with #BlackFriday, #CyberMonday, and the 12.12 sales coming up in the next few weeks, but before tapping on the check out button, ask yourself: “Do I really need this?” For instance, if your current electronic device isn’t working, try sending it for repair, to save it from the landfill. And if it is beyond repair, don’t forget to drop it in a recycle bin. More at https://go.gov.sg/nea-recycle-e-waste #RecycleOurEWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #915 · 14.10.2024 г., 05:36

Give your e-waste a second life by recycling them this International E-waste Day 📱💻♻️ Find out more about how to recycle your e-waste at go.gov.sg/e-waste Let’s also reduce the amount of e-waste generated by: - Considering if you really need to buy new a product or if the current one can be repaired - Choosing second-hand products over new products - Donating devices that are in good condition to those who could put them to better use #RecycleRight#RecycleOurEWaste#IEWD2024#InternationalEWasteDay2024#DataSecurity