Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🆕Appointments here!
We glad to present you a 1st version of Appointment system. This journey was challenging, interesting and took 4 months. We faced complex challenges where we had to create a new approach.
🌐 Now you can discover all kind of businesses in one mini app with convenient map. Your country, your service, your time!
🛍 We know that our users want to provide their customers with only the best service that will work 24/7 without interruption. All on one page and app. Provide services and book services from others. The era of Telegram appointments is now open!
And don't forget, almost all new businesses will be available for viewing and researching by thousands of Callegram users. Don't miss the opportunity to be the first to create a business!
App | #Callegram#MiniApps#Appointments
🔜 We're at the finish line!
This is what the booking process will look like from the client's side. Choose the time, master and service that is convenient for YOU 👍
App | #Callegram#MiniApps#Appointments
✏️Find a Cool Service Directly in @CallegramBot? Why Not?
We’re almost here with a new huge update — Appointments.
Our users will be trying to find an awesome services directly in the mini app.
We’re doing our best!
App | #Callegram#MiniApps#Appointments
🚨AI Takes Your Job
And this is awesome! Today we’ve tried our first version of AI Appointments. And it works really great!
In the near future your clients will chat with you about services and AI will assist you with confirming appointments.
Different languages, text and voice messages. No more annoying work!
Be ready for the feature right now. Create your business
🔗t.me/CallegramBot/subscribe_business
App | #Callegram#MiniApps#AI#Appointments
🔜Appointments In Callegram
This is a big part of our service and we want to share with you a first sneak peak.
⚠️ This feature is not available now. Check our news below.
Users. You will get an option to make an appointment directly in Telegram for your favorite services. You don’t need to make a call or visit the service location. Just few clicks and you will get what you want + reminders about upcoming service.
Businesses. Setup your businesses, locations, specialists, their schedules and services. Automate your handwork and launch your services in Telegram within a few minutes.
Marketplaces. If you want to use our Callegram system in your flow and give your merchants opportunity to create an appointment schedule, please contact @krimon
👀 Stay tuned and check the news in our channel
#MiniApps#Telegram#Business#Appointments
🤫Page Of Businesses
Users, are you ready to make appointments in a few clicks?
Businesses, are you ready to provide your services seamlessly?
🙂 Stay tuned
#Appointments#MiniApps#Business#CallegramBusiness
⚙️We've automated everything for you
Now your business' schedule is sent automatically if the person writes the words ‘Book’, ‘Appointment’
To activate the function:
1) Create a business with services;
2) Pay subscription;
3) Add @CallegramBot in Telegram settings in "Telegram Business - ChatBots".
Now your customers will get a specific message with option to make an appointment.
Don't waste time on routine, get down to business. Callegram optimises your work 💰
App | #Callegram#MiniApps#Appointments#TelegramBusiness