Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
This workshop was the culmination of months of thoughtful preparation, deep dives, and collaboration across teams — all driven by a shared ambition to reimagine how we can serve better, adapt faster, and create greater impact for Singapore.
It was inspiring to see the energy, honest reflections and collective commitment in the room. As One IRAS, we’re charting the path towards a more connected, innovative, and future-ready organisation.
#lifeatiras#irassg
We also recognised the contributions of our Accredited Tax Specialists (ATS) through the Technical Contribution Award, inducted our 15 newly accredited tax specialists, and celebrated the achievements of our Book Prize winners for the Advanced Tax Programme.
Thank you to the 2025 ATC Organising Committee and all who have made this event possible! 🎉
#lifeatIRAS#irassg
We kay-poh and asked our colleagues what they do at IRAS 👀 Psst: it’s not all about taxes!
Swipe to see some of the different roles we have here ➡️
Explore the roles available at go.gov.sg/lifeatiras
#LifeatIRAS#irassg
What does a UI/UX Designer at IRAS do? Watch as our colleague's children take a guess at what she does for work, while she shares her thoughts on balancing work and motherhood.
Wishing all the incredible mothers out there a Happy Mother's Day! 💐❤️
#irassg#lifeatIRAS
You heard it here first! IRAS is more than just Singapore's tax authority - we're a community of passionate individuals contributing to Singapore’s growth and progress.
Join us today at go.gov.sg/lifeatiras
#irassg#lifeatiras
Less than a week until the YA 2025 Corporate Income Tax filing deadline.
All companies are reminded to file their YA 2025 Corporate Income Tax Return (Form C-S/ Form C-S (Lite)/ Form C) at mytax.iras.gov.sg by 30 Nov 2025.
#irassg#CorporateIncomeTax2025
Looking for the perfect match this Corporate Income Tax season? Let’s find your “wholly and exclusive” matches. Swipe right on the deductible expenses and swipe left on non-deductible expenses!
Reminder: File your YA 2025 Corporate Income Tax returns by 30 Nov 2025
Learn more: go.gov.sg/businessexpenses
#CorporateIncomeTax2025#irassg
Even if your company has been steeping in dormancy mode all year, just like cold brew tea slowly steeping in the fridge... you still need to file your YA 2025 Corporate Income Tax Return for your Dormant Company, unless you have obtained a waiver to file the return.
Reminder: filing of the YA 2025 Form C-S, Form C-S (Lite) or Form C by 30 Nov 2025 is compulsory for all companies.
Find out how to file as a dormant company or how to apply for a waiver at go.gov.sg/irasdormantcompanies
#CorporateIncomeTax2025#irassg
When you (girl-)bossed too hard that you have to pay taxes
🌟 If your total annual net trade income was over $6,000 (or your total taxable income exceeded $22,000) last year, remember to include your passion projects in your tax filing by 18 April!
Learn more about tax obligations for online sellers and service providers at go.gov.sg/tax-guide-online-sellers-service-providers
More at go.gov.sg/taxseason2025
#TaxSeason2025#irassg
Have you filed your income tax return yet? Remember to do so by 18 Apr. Avoid these common mistakes:
1. Not filing your income tax return when you need to
2. Incorrect relief claims
3. Incorrect expense claims
4. Not clicking the “submit” button
5. Not informing IRAS when you discover mistakes in your submission
Check out our handy e-Filing Guide if you are unsure of your tax filing: go.gov.sg/efilingguide
More at go.gov.sg/taxseason2025
#TaxSeason2025#irassg
As IRAS' Group Tax Specialist, Richard supports his team in reviewing tax compliance matters and complex issues. He also provides training and consultations on IP valuation as an IP Valuation Specialist.
Recently, Richard was appointed as Tax Academy's Specialist & Curriculum Development Specialist. In this role, he develops training programmes for tax professionals, equipping them with relevant and practical insights whilst fostering collaboration within the tax community.
Read on to discover how Richard's diverse roles complement one another in his daily work.
#irassg#irasfam#lifeatiras
Transforming how we do taxes: DON-API is one of IRAS’ ongoing efforts to partner with our tax ecosystem to make taxpaying easier and more seamless.
Meet the all-girls team from IRAS behind this game-changing initiative.
Find out more at https://www.iras.gov.sg/who-we-are/what-we-do/annual-reports-and-publications/taxbytes-iras/engagement/making-tax-submission-simple-for-ipcs
#lifeatiras#irassg#irasfam