Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
When paying respects this Qing Ming, let’s continue to be socially responsible and observe #SafeDistancing measures. As crowds are expected at Choa Chu Kang Cemetery and government-managed columbaria, visitors are advised to send 2 representatives per household (with not more than 8 pax per group). The opening hours will be extended to 24-hours, with effect from 20 Mar until 18 Apr 2021.
Visitors driving to Mandai Columbarium during peak days will also be required to book an appointment. Visit www.nea.gov.sg/qingming2021 for more information.
From 12 Sep 2020, weekend visitors to the 4 popular markets (Geylang Serai Market, Chong Pang Market, Block 20/21 Marsiling Lane, and Block 505 Jurong West Street 52) will not be subject to the odd/even date entry restriction. However, the caps on the number of patrons allowed in the market at any one time will still be in place, to ensure sufficient #SafeDistancing. More information available at https://go.gov.sg/nea-lifting-entry-restriction-markets-12sep
During Phase 2, you may leave your home to smoke, but do so in an area where smoking is not prohibited, and observe #SafeDistancing requirements. To protect yourself and others around you, do put your mask back on as soon as you have finished smoking. From 19 Jun, Designated Smoking Areas along the Orchard Road No Smoking Zone can re-open with safe distancing measures. Smoking corners beyond the Orchard Road No Smoking Zone, can also re-open with the necessary safe distancing measures in place. www.nea.gov.sg/post-circuit-breaker-measures
From 22 Apr 2020, access to 4 popular markets will be restricted based on the last digit of patrons’ NRIC or FIN numbers, to ensure effective #SafeDistancing and safeguard public health. Patrons with NRIC/FIN ending with:
- an even last digit (0, 2, 4, 6, 8) can only visit on the even dates of the month
- an odd last digit (1, 3, 5, 7, 9) can only visit on the odd dates of the month
These 4 markets are Geylang Serai Market, Block 104/105 Yishun Ring Road (Chong Pang Market), Block 20/21 Marsiling Lane Market, and Block 505 Jurong West Street 52 Market. More information available at www.facebook.com/NEASingapore/posts/2589759427912055
If your parents or older relatives do their grocery shopping at these 4 popular markets, do share the guide (available in 4 different languages) with them! Download a copy from https://www.facebook.com/NEASingapore/posts/2590540227833975
Dine-in at #OurHawkerCentres resumes from 19 Jun! Whilst you may be excited to meet with your friends, limit the group to 5 people or less and continue to observe #SafeDistancing measures – use unmarked seats/tables, keep 1 metre apart from others, and only remove your masks when eating.
At our markets, continue to stand within the boxes marked on the floor, to maintain a safe distance. Access to the 4 popular markets will continue to be restricted based on the last digit of your identification number. More information available at www.nea.gov.sg/media/news/advisories/index/safe-management-measures-in-phase-2-at-hawker-centres-and-markets
Need your essentials? In addition to wearing a mask to buy essentials at the supermarket, schedule your grocery run on a weekday and avoid the peak periods, or opt for delivery instead. Let’s take #SafeDistancing seriously, and work together to stop the spread of COVID-19. #SGUnited
Planning dinner with your friends? Due to #SafeDistancing, there may be limited seating capacity at many places, so call in advance to make reservations first. Otherwise, opt for takeaway (bring your own containers!) or delivery 😊#SGUnited#FightCOVID19
#SafeDistancing applies everywhere – even when choosing fish and vegetables at the markets! If you have elderly neighbours or family members, help them with their marketing instead so that they can #StayHome and stay safe. #SGUnited
Only sit on seats without markings when dining in at #OurHawkerCentres to maintain #SafeDistancing. If the seating capacity is limited, #BringYourOwn clean containers and choose to take-out instead. Let’s unite to #FightCOVID19 together! 💪#SGUnited
Let’s remember to stay at least a metre apart from each other. We wouldn’t want all the effort and resources of the past few months to go to waste. Dining in at #OurHawkerCentres? Let’s not forget to #ReturnOurTrays and #BinOurTissues after enjoying the meal! #SGUnited#SafeDistancing#FightCOVID19