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

Резултати

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

Пребарај: #skit

当前筛选 #skit清除筛选
IRAS

@irassg · Post #725 · 22.12.2023 г., 06:30

Navigate the right GST rate to pay for transactions spanning the rate change with new mummy and her bestie! 💁‍♀️💡 A transaction is considered to span the GST rate change if one or two of the following events takes place wholly or partially on/after 1 Jan 2024: - The issuance of invoice by supplier - The receipt of payment by supplier - The delivery of goods or performance of services More info at go.gov.sg/irasgst-rc-consumers #GST#GSTRateChange#skit#iras#irassg

IRAS

@irassg · Post #702 · 06.12.2023 г., 04:02

Is delulu the solulu? At least, she gained some tax tips on Supplementary Retirement Scheme (SRS) contributions! 💰🤣 Grow your savings by contributing to your SRS Account today! You will be eligible for tax reliefs in Year of Assessment 2024 if you make contribution to your SRS Account by 31 Dec 2023*. SRS contributions are capped yearly at $15,300 for Singapore Citizens and Permanent Residents and $35,700 for foreigners. Do note that there is an overall cap of $80,000 on the total amount of all tax reliefs that can be claimed (including any relief on SRS contributions) for a year. Details and qualifying conditions: https://www.iras.gov.sg/taxes/individual-income-tax/basics-of-individual-income-tax/special-tax-schemes/srs-contributions *You are advised to check with your SRS bank operator about the cut-off date for SRS contributions. #taxtips#retirement#invest#skit#girlsvsguys#irassg#iras

IRAS

@irassg · Post #707 · 08.12.2023 г., 06:00

Spread some year-end cheer while saving on your taxes! 🥳✨ Enjoy tax deductions of 2.5 times the qualifying donation amount in Year of Assessment 2024 when you donate to any approved Institution of a Public Character (IPC) by 31 Dec 2023. You will not need to declare the donation amount in your Income Tax Return as tax deductions for qualifying donations will be automatically reflected in your tax assessments based on information from the IPC. Details and qualifying conditions: https://www.iras.gov.sg/taxes/other-taxes/charities/donations-tax-deductions #taxtips#donations#spreadjoy#seasonsgreetings#skit#irassg#iras

IRAS

@irassg · Post #775 · 09.02.2024 г., 06:50

Bracing for the annual CNY “kaypoh” questions too? 😅 Here’s one thing less to worry about – use the Personal Relief Checker (go.gov.sg/personalreliefchecker) to discover the personal tax reliefs you're eligible for in the upcoming tax season! 🔍 #pov#skit#cny2024#asianrelatives#taxreliefs#taxtips#irassg

IRAS

@irassg · Post #711 · 13.12.2023 г., 05:09

Yasss to being a financially savvy kween! 🙌👑 It’s never too soon to secure the bag for your (and your fam’s) retirement 🌟 Top up your own and/or those of your family members’ CPF Special/Retirement or Medisave Account by 31 Dec 2023 to enjoy the CPF Cash Top-up Relief in Year of Assessment 2024. Do note that there is an overall cap of $80,000 on the total amount of all tax reliefs that can be claimed (including any relief on CPF Cash Top-ups) for a year. Details and qualifying conditions: https://www.iras.gov.sg/taxes/individual-income-tax/basics-of-individual-income-tax/tax-reliefs-rebates-and-deductions/tax-reliefs/central-provident-fund-(cpf)-cash-top-up-relief #taxtips#retirement#cpf#skit#asianmums#giftideas#irassg#iras