Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
[BPLRT] UPDATE: Free regular bus services between #ChoaChuKang and #Bukit Panjang are available. If your journey has been affected, you may download an e-Travel Chit as proof of your travel at https://bit.ly/39HsrAl.
- SMRT
🎸Singer and surfer Jack Johnson to give a concert in Bali
📆 Jack Johnson will be coming to Bali in 2025 for a chamber event to be held at Uluwatu Surf Villas on Bukit Peninsula on June 18, 2025 and it will be one performance only.
🎫 Less than 1,000 tickets are expected to go on sale. It costs Rp 2,205,000 for adults and Rp 815,000 for children 5-12 years old. Food and drinks will be available all evening and the event will be completely outdoors. It will be held in all weather conditions.
ℹ️ The singer has become known for his soft acoustic music that has become a symbol of the surf culture of the 2000s (many have heard one of his most famous tracks Better Together. Jack Johnson rose to fame after the release of surf movie The September Sessions, where he performed his first songs.
@BaliNews
#events#concerts#Bukit
🍊Mandarin Oriental to open new hotel in Bali
🏨 Famous Mandarin Oriental plans to open a luxury resort on the Bukit Peninsula in 2027. The new project will feature 110 rooms, suites and villas, all of which will blend in with the natural surroundings.
🕺 Renowned interior designer Jeffrey Wilkes is involved in the project. He designs luxury hotels and residences.
📍 The location of the resort will be 30 minutes from the international airport. Close to popular tourist areas such as Jimbaran, Uluwatu and Nusa Dua.
@BaliNews
#places#hotels#goodnews#Bukit
⛔The canyon to Tanah Barak Beach has been closed to private vehicles
📰 One of Bukit's most photogenic spots near the famous Pandawa Beach, Tanah Barak Canyon, is now off-limits to private vehicles. Tourists will have to walk or take a paid shuttle service.
🏝 Visitors will now be able to enjoy the beauty and tranquillity of Tanah Barak without the passing motorbikes and autos.
@BaliNews
#trasport#roads#Bukit#beaches
🛣Details about the construction of a district road in Bukit
District authorities are set to solve the road issue in Uluwatu by laying a new district road.
Construction of the first section from Siligita village to Sawangan in Nusa Dua district has already started.
The original idea was to extend the toll road, which now runs from the airport to Nusa Dua, all the way to Uluwatu.
Right now, traffic on the main road jl. Uluwatu is difficult because it is both a hub of commerce and the main thoroughfare of the area, used by everyone from locals to construction vehicles and tour buses.
The land acquisition budget for 2024 will be $16 million, with the next one already promised to increase to $19 million.
According to an insider in Bali's land office, all consideration of new housing development in the green zone on Bukit is now halted just in time for the land acquisition for the new roads.
@BaliNews
#roads#roads#authorities#Bukit#Uluwatu#NusaDua