Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⛳International Golf Day on 15 June
📍 Marriott International Corporation is holding its annual International Charity Golf Day in Bali. This year's event will be held on 15 June at the National Golf Club in Nusa Dua.
🏌️♀️ Everyone can join this elite and expensive game, not only through participation in tournaments, but also during the evening programme, which the organisers announce as a kind of networking.
🎷 The festive evening will take place at the Westin Resort Nusa Dua at 18:30 the same day. Everyone is welcome to attend. The dinner will feature a buffet of international cuisine with beer, wine and soft drinks. In addition, guests can expect door prizes, auctions, and an entertainment programme with live music.
@BaliNews
#wheretogo#events#NusaDua
🎾Tennis in Bali: Nusa Dua opens clubhouse for ATP level tournaments
📍 The Bali Golf and Racket Club has opened in Nusa Dua, ready to host ATP tournaments in the future. It is the newest sports complex located in the heart of one of Bali's most prestigious resort areas, The Nusa Dua, which is famous for its five-star hotels and unique infrastructure.
🏆 The club was the first of its kind on the entire island. With its appearance, Bali acquires the status of not only a paradise island, but also a center for international tennis tournaments and sports tourism.
@BaliNews
#goodnews#sport#NusaDua
🎶TGIF 2025 music festival will return to Bali in May
The event promises to be one of the highlights of the music season in Bali.
📆 May 24-25
📍 At a new venue in Port of Benoa
ℹ️ In addition to concerts and live music, guests can expect food courts from local businesses, photo zones, interactive entertainment and relaxation areas. Parking and shuttles to shuttle guests are available for convenience.
🎫 Tickets are on sale now: one-day, two-day and VIP packages are available on the official website from Rp 150.000.
#events#festivals#wheretogo#NusaDua@BaliNews
🛎The first Waldorf Astoria hotel opens in Bali: second attempt
📰 The Hilton hotel group is expanding its presence in Bali. Waldorf Astoria Bali will be located between the Hilton and Kempinski hotels in Nusa Dua, 14.5 km from Ngurah Rai International Airport. The hotel is scheduled to open in late 2027.
🏨 Waldorf Astoria Bali will include 71 spacious villas and 68 guest suites, as well as the standard infrastructure for a chain hotel — restaurants, a spa, a fitness center, children's entertainment, and event rooms.
ℹ️ Waldorf Astoria had already announced the opening of its hotel in Bali in 2014. At that time, the location was chosen near Pandawa Beach in the south of the island. The opening was planned for 2027, but something went wrong. The massive concrete unfinished building can still be seen on the cliff to the left of the entrance to Pandawa Beach.
#places#realestate#development#NusaDua@BaliNews
🚤New Bali water taxi service launches for tourists
📰 A new marine transportation service, Bali Marine Water Taxi, has been launched in the popular resort area of Benoa (Nusa Dua) in Bali.
📍 The tourist cab service connects the seaports of Tanjung Benoa, Serangan and Pedungan (South Denpasar).
35 minutes. That’s all it takes. No traffic, no stress - just ocean views and open horizons. Uluwatu is calling.
👍 This is just one of the many sea routes Bali plans to develop in the coming months.
@BaliNews
#goodnews#places#services#transport#tourism#NusaDua
🛣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