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

Резултати

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

Пребарај: #hdbesavvy

当前筛选 #hdbesavvy清除筛选
HDB

@SingaporeHDB · Post #2743 · 20.03.2025 г., 10:03

Mirror, mirror on the wall, who's the most #HDBeSavvy of them all? 👑✨ Swipe for info on buying an HDB flat and start your home-buying journey strong. Psst… our next BTO launch drops this July!

Hashtags

HDB

@SingaporeHDB · Post #1620 · 16.02.2023 г., 07:01

Starting on your BTO flat renovations soon? Read the FAQs we’ve compiled so you can #HDBeSavvy during your reno journey 🛠

Hashtags

HDB

@SingaporeHDB · Post #1456 · 27.10.2022 г., 09:01

#HDBeSavvy and check out this guide to priority schemes that can improve your chances when balloting for a flat in BTO/SBF exercises 😊 📖 Read our guide to priority schemes 👀 Check out our guide to CPF housing grants

Hashtags

HDB

@SingaporeHDB · Post #1206 · 20.04.2022 г., 02:30

Eyeing a resale flat? #HDBeSavvy and use these resources to: 📝Check your eligibility to buy a resale flat and apply for an HDB housing loan 📊View resale statistics (e.g. median resale prices by town and flat type) 📍Check if an HDB flat is within 4km of another residential property to qualify for the Proximity Housing Grant 📥Apply to buy a resale flat via the HDB Resale Portal 📚Sign up for our resale seminars to learn more about resale policies and procedures Read more about resale flats: ◾️Your Guide to Buying a Resale HDB Flat ◾️Buying a Resale Flat: What to Look Out For ICYMI, check out our resource kit on financial planning.

Hashtags

HDB

@SingaporeHDB · Post #1197 · 12.04.2022 г., 06:31

Working out the math for your flat? #HDBeSavvy and use these resources to: 💰Calculate your budget 📥Apply for an HDB Loan Eligibility Letter (HLE) 📋Compare loan packages offered by participating Financial Institutions (FIs) 📑View the customised payment plan for your homebuying journey Read more about financial planning: ◾️How to decide between a loan from HDB and a loan from an FI ◾️A guide to CPF Housing Grants

Hashtags

HDB

@SingaporeHDB · Post #1017 · 19.11.2021 г., 02:01

Planning to buy a 3-room flat in this sales exercise? We’ve done the math for you so you can #HDBeSavvy in planning your finances 🤓 🔗 If you need more help, visit https://homes.hdb.gov.sg/calculator

Hashtags

HDB

@SingaporeHDB · Post #1015 · 18.11.2021 г., 02:01

Choosing among the 4,501 BTO flats on offer across 6 locations? #HDBeSavvy by comparing your options! P.S. You can also tap on the Enhanced Housing Grant of up to $80,000 to finance your flat purchase, depending on your income. Other resources: 🧐Study the flats/location on offer, and their estimated completion dates 📝Check your eligibility 💰Work out your budget

Hashtags

HDB

@SingaporeHDB · Post #1008 · 11.11.2021 г., 04:24

Find out more about the differences between buying a BTO and resale flat under the Singles Singapore Citizen Scheme in our #HDBeSavvy cheatsheet! ➡https://t.me/SingaporeHDB/775

Hashtags

HDB

@SingaporeHDB · Post #902 · 14.08.2021 г., 04:00

Planning to buy a 3-room flat in this sales exercise? We’ve done the math for you so you can #HDBeSavvy in planning your finances 🤓 🔗 Visit https://homes.hdb.gov.sg/calculator to calculate your own flat budget, including housing loan estimates from HDB and participating financial institutions!

Hashtags

HDB

@SingaporeHDB · Post #971 · 13.10.2021 г., 01:09

🍋 When life gives you lemons… here are 4 #HDBeSavvy things to do while waiting for your BTO flat to be ready. 🔗#DYK? Average waiting time for ongoing BTO projects, including pandemic-induced delays, has remained between 4 to 5 years.

HDB

@SingaporeHDB · Post #1223 · 11.05.2022 г., 06:45

Planning to #BTOgether at the upcoming Sales Launch? #HDBeSavvy and use these resources to: 📝Check your eligibility to buy a BTO flat and/or apply for an HDB housing loan 🗺View the locations on offer at upcoming Sales Launches via the HDB Flat Portal Read more about BTO flats: ▪️A Guide to Buying a BTO Flat ▪️Expenses First-Timer BTO Flat Buyers May Overlook ▪️HDB Does Not Price Flats to Recover Land and Building Costs ICYMI, check out our resource kits on financial planning and resale flat buying.

HDB

@SingaporeHDB · Post #1448 · 16.10.2022 г., 07:01

Received the keys to your new flat and can’t wait to start designing your dream home? From designing your kitchen island, to choosing the right lights and TV consoles, or even ideas on baby-proofing, here are resources that can help you #HDBeSavvy: 💭 Be inspired by design ideas, including our curated list of IG accounts to follow for interior design inspo 🔎 Explore our HDB showflats at our virtual My Nice Home Gallery 👀 Peek into home tours by fellow HDB residents Now that you have #saidyes to your new home design, we also have tips on how to maintain your home after move-in.

12
ПретходнаСтраница 1 од 2Следна