Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#ICYMI
Check out our latest blog posts:
1️⃣ Minimize Gas Fees on opBNB
https://www.bnbchain.org/en/blog/how-to-minimize-gas-fees
2️⃣ BNB Chain's AI Ecosystem: Discover our AI projects driving innovation.
https://www.bnbchain.org/en/blog/untitled-36
3️⃣ Trading Volume Incentive Program: Win up to $250,000!
https://www.bnbchain.org/en/blog/introducing-bnb-chains-trading-volume-incentive-program
4️⃣ BNB Chain Pizza Day: Celebrate and win $10,000 in $BNB!
https://www.bnbchain.org/en/blog/bnb_pizza_ai_challenge
What's your favorite AI project on BNB Chain? Let us know!
#ICYMI
This past week, we published the following blog articles.
1️⃣Airdrop Alliance Chapter 2: Campaigns Guide
–
Get ready to embark on a journey filled with thrilling quests, exclusive drops, and rewarding experiences. Here's a comprehensive summary of what awaits you for the extra rewards!
https://www.bnbchain.org/en/blog/untitled-34
2️⃣New Projects on BNB Chain (27th April - 11th May)
Let's welcome some new projects to the BNB Chain ecosytem!
https://www.bnbchain.org/en/blog/new-projects-on-bnb-chain-27th-april-11th-may
3️⃣BNB Greenfield Erdos Hardfork
The BNB Greenfield network is about to undergo the Erdos hardfork, introducing major updates and enhancements to the platform.
https://www.bnbchain.org/en/blog/bnb-greenfield-erdos-hardfork
4️⃣What is LSDFi? The Fusion of Liquid Staking Derivatives and DeFi
LSDFi, or Liquid Staking Derivatives in Decentralized Finance, allows staking cryptocurrencies while keeping them liquid.
https://www.bnbchain.org/en/blog/what-is-lsdfi-the-fusion-of-liquid-staking-derivatives-and-defi
5️⃣A Recap of BNB Chain Hackathon 2024 Q2: OneBNB - Coding the Future Workshops
The BNB Chain Hackathon 2024 Q2 served as a hub of creativity and exploration, where developers from across the globe converged to push the boundaries of blockchain technology.
https://www.bnbchain.org/en/blog/a-recap-of-bnb-chain-hackathon-2024-q2-onebnb-coding-the-future-workshops
6️⃣How To Use Blobs On BNB Greenfield
BNB Greenfield revolutionizes decentralized storage and data management with its latest addition, "BlobHub."
https://www.bnbchain.org/en/blog/how-to-use-blobs-on-bnb-greenfield
Are you bullish on decentralized storage chains? Have you checked out Greenfield yet? Let us know.
📢The Weekly Wrap – 3 April 2026
1) U-Save and S&CC rebates coming your way🎉
Look out for the first quarterly rebates this April!Eligible households can receive up to $190 of U-Save and 1 month of S&CC rebates to defray living expenses.
🔗 Check how much you can receive: https://www.govbenefits.gov.sg/
2) #ICYMI Five schemes take effect from 1 April ✅
Check out how some of the newly-effected schemes will affect you.
🔗 More info: https://go.gov.sg/new-april2026
📢 The Weekly Wrap – 16 January 2026
1) Serving Singaporeans better through enhanced data sharing 💻
The Public Sector (Governance) Act (PSGA) (Amendment) Bill enables public agencies to share data with external partners to better serve Singaporeans.
Agencies must first ensure 3️⃣ safeguards are met:
1. There is a legitimate purpose for data-sharing with external partners
2. Obtain Ministerial authorisation before sharing data
3. External partners must have data protection measures
📎 Learn more: go.gov.sg/tww-psga
2) ‘One Patient, One Health Summary, One Care Journey’ 👨⚕️
The Health Information Bill requires all healthcare providers to share key patient information with the National Electronic Health Record (NEHR) system for better coordinated care and lower costs. NEHR access is for patient care needs only:
1. Only healthcare providers can access NEHR
2. Doctors can “break-glass” for medical emergencies only
3. Accessing NEHR for employment or insurance is strictly prohibited
📎 Learn more: go.gov.sg/tww-hib
3) Final shout-out to experience Light to Night Singapore! ✨
#ICYMI Light to Night Singapore is back in its 10th edition to illuminate the Civic District!
🗓️ 9-31 Jan 2026 (final two weeks!)
📌 Various locations in National Gallery Singapore and the Civic District
#ICYMI: The 15th Parliament of Singapore opened with President Tharman Shanmugaratnam’s Address, setting out the Government’s strategies for the future. From redefining success, to deepening our multicultural identity, to charting our destiny as a nation in a more unsettled world, the President outlined how we can ensure an inclusive and resilient Singapore. Swipe through these images for several key quotes.
➡️ Stay tuned to gov.sg for all the latest updates on the 15th Parliament.
📢 The Weekly Wrap – 22 August 2025
1) #ICYMI: National Day Rally 2025 🇸🇬
Catch some of the key highlights of PM Lawrence Wong's National Day Rally speech on shaping the next chapter of our Singapore Story—beyond SG60.
🔗 Read more: instagram.com/p/DNfq5SMSleR
2) Vaping is ILLEGAL and more dangerous than you think ❌
Take a stand against vaping. Know the facts, know the risks. Bin it and quit now.
🔗www.gov.sg/stopvaping
3) What if you could meet your future self? 🤔
Step right into the future at the SG60 Heart&Soul Experience! ✨ Discover what tomorrow's Singapore could look like through immersive and interactive stories, personalised just for you!
🗓️ 26 Aug to 31 Dec 2025
📍 Orchard Library
🎟️ Admission is FREE
🔗 Get your tickets now: heartandsoul.gov.sg
📢The Weekly Wrap – 15 August 2025
1) Tune into the National Day Rally (NDR) this Sunday🇸🇬
Prime Minister Lawrence Wong will deliver his NDR speech on 17 Aug. Tune in live at 6.45pm on TV and radio stations, or watch it on Prime Minister’s Office’s YouTube channel.
🔗 Watch it live here: https://www.youtube.com/pmosingapore
2) What do you want to see in your future ‘hood?
Look around – what do YOU want to see being built? Let your imagination run free! Need some inspo? Watch this: https://instagram.com/p/DNW-XTZKWj-/
👉 Share your ideas for the URA Draft Master Plan 2025: https://www.uradraftmasterplan.gov.sg/feedback
3) #ICYMI Meeting your housing needs!
From building more BTO flats faster to upgrading older HDB estates, here’s how the Government is keeping public housing affordable and accessible for you: https://instagram.com/p/DNK56V2qk9Q/
📢 The Weekly Wrap – 1 August 2025
1) #ICYMI Stiffer penalties for those who import, sell or distribute etomidate-laced vapes
Etomidate will be listed as a Class C drug under the Misuse of Drugs Act as an interim measure to enable tougher enforcement measures.
Visit go.gov.sg/bin-vapes to locate the nearest e-vaporisers bin.
2) Last weekend for Together, for Better roadshow!
Catch us at our last roadshow to learn more about Forward SG measures this weekend! Stand to win vouchers and exclusive giveaways!
📍Bishan Junction 8, Atrium Level 2
📆 2-3 August, 11am – 8pm
Find out more: togetherforbetter.gov.sg/events-and-roadshow
3) What would you do when terror strikes?
Catch our local influencers spring into action in a terror simulation in SGSecure’s new web series!
🔗 Watch Ep 1 here: https://go.gov.sg/whatwouldyoudowhenterrorstrikesyt
📢 The Weekly Wrap – 25 July 2025
1) Where can you use your SG60 vouchers?🇸🇬
Step 1: Eligible Singaporeans can now claim your vouchers at go.gov.sg/sg60v
Step 2: Find out where you can use them here: go.gov.sg/sg60voucher
2) Get a head start in your job hunt era
Need some support in finding the right job match after graduation? Or maybe you’re just looking for some career advice?
Make 🔗CareerHealth.sg the next stop in your job search and take the quiz for useful career advice!
3) #ICYMI Better Support for Families to Live Closer
HDB’s Family Care Scheme (Proximity) takes effect from July 2025’s Sales Exercise, supporting parents and children with priority access when applying for a new flat to live with or near each other.
🔗 Find out more at go.gov.sg/hdb-priority-schemes-fb
📢 The Weekly Wrap – 23 May 2025
1️⃣ PM Wong announces new Cabinet
Prime Minister Lawrence Wong has announced the line-up for his new Cabinet, which now includes three Coordinating Ministers.
🔗 Watch the Swearing-in Ceremony live at 7.45pm on PM Lawrence Wong's YouTube (https://youtube.com/@lawrence_wong)
2️⃣#ICYMI Support for workers and fresh graduates
As part of the Singapore Economic Resilience Taskforce (SERT), the Government will explore stepping up training opportunities for workers and job assistance for fresh graduates.
🔗 Find out more: https://go.gov.sg/sert-workers-tww
3️⃣Last weekend of HOMEGROUND: A Singapore Heritage Fest Experience✨
Explore Singapore’s intangible cultural heritage at the last weekend of HOMEGROUND. From live performances to interactive activities and ‘makan’ villages, fun-filled weekend awaits!
🔗Check it out: https://go.gov.sg/homeground-tww
📢 The Weekly Wrap – 11 April 2025
1) #ICYMI PM Lawrence Wong on US tariffs
PM Lawrence Wong spoke about the impact of the US tariffs on Singapore and the global economy. He assured Singaporeans that the Government will provide support to those affected.
🔗 Watch more here: https://www.instagram.com/p/DIMIy7dP_sU/
2) 👀 Spotted: The Together, for Better roadshow in your ‘hood
Psst… the roadshow’s been making its way around SG, and this weekend it’s hitting Bedok and Punggol!
Swing by to:
✅ Check out the interactive exhibits
💼 Get professional advice on jobs and upskilling
🎁 Join quizzes and win prizes
See you at Bedok Town Square and One Punggol, from 11am-8pm this weekend!
🔗 Here’s a sneak peek: https://www.instagram.com/p/DIOS4IhI3f2/