Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🎮 Singapore River Quest: Level Up IRL 🎮
Ready to game outside your room?
🧩 12 puzzles to crack
🏆 Prizes up for grabs
🏙️ Level up your knowledge of the SG River and its history
Play solo or grab your squad and explore this outdoor game. More deets: go.gov.sg/singapore-river-quest
#KeepSGClean#YearofPublicHygiene
🌴 It's always a treat to take a stroll around Marina Bay Sands in the evenings. If you are heading there to catch the fireworks during NDP previews, don’t forget to bin your litter properly while enjoying the view. Together, let’s #KeepSGClean! #YearOfPublicHygiene
Enforcements at the adjusted Orchard Road No Smoking Zone begins today, 1 Apr 2024. Watch this video go.gov.sg/orchard-road-no-smoking-zone-apr2024 or visit www.nea.gov.sg/ORNSZ to find out more.
Together, let’s #KeepSGClean! #YearOfPublicHygiene
Ever wondered what happens after a waste truck collects your waste? 🚮🚮🚮
With current disposal rate, Semakau Landfill is projected to reach full capacity by 2035. 🗑️🗑️🗑️
Let’s take action towards a more sustainable Singapore - say yes to reducing waste and do your part today! 👏🏻👏🏻👏🏻
#KeepSGClean#YearofPublicHygiene
#SGBudget2024 Opening of Singapore’s first Enviro Tech Innovation Hub in Apr 2024 – an industry-led collaboration to advance sustainable environmental cleaning and integrated facilities management; and support the cleaning workforce. More info at www.nea.gov.sg/year-of-public-hygiene#YearofPublicHygiene
#SGBudget2024 To keep the incidence of vector-borne diseases low, we will focus on tackling rat issues at source and combating dengue by expanding Project Wolbachia - Singapore. More info at www.nea.gov.sg/year-of-public-hygiene#YearofPublicHygiene
#SGBudget2024 The Ministry of Sustainability and the Environment has designated 2024 as the #YearofPublicHygiene to galvanise all to reinforce good hygiene practices for our collective well-being.
In this year, we will:
✅ Continue to reinforce high standards of public hygiene
✅ Step up efforts across 5 key areas
More information at www.nea.gov.sg/year-of-public-hygiene
Happy World Wetlands Day!
Wetlands are vital ecosystems that support a rich variety of wildlife! 🦀🦦🌱
As you wander through the wetlands of #StunningSingapore, such as the Sungei Buloh Wetland Reserve, be a gracious guest and bin your litter properly. Let’s do our part to #KeepSGClean and safeguard our wetlands for future generations. #YearofPublicHygiene
👨👩👧👦 Holiday Fun Pick - Play:Date exhibition at National Museum of Singapore 🏛️
As we marvel at the exhibitions and architecture of our oldest museum, let's play our part in preserving its beauty by keeping it litter-free.
#StunningSingapore#KeepSGClean#YearofPublicHygiene
Planning to catch the fireworks in the Esplanade area tomorrow? While enjoying the stunning displays, let’s make sure to keep our #StunningSingapore shiny and sparkling by binning our litter properly.
Together, let’s #KeepSGClean🌟#YearOfPublicHygiene
🌴✨ Discover the serene beauty of Singapore Botanic Gardens. Admire the water lilies floating on a stunning lake amidst picturesque palm trees. Our #StunningSingapore spaces are truly breath-taking, and it's up to us to keep them that way! Let's ensure these public spaces stay litter-free and clean. #KeepSGClean#YearofPublicHygiene#StunningSingapore
Step back in time with the heritage houses of Joo Chiat Road. These Peranakan beauties are a feast for the eyes and the soul. While exploring, let’s also take care of our #StunningSingapore spaces and #KeepSGClean. #YearofPublicHygiene