Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
GM OneEarth community, it's been a while! 🎆
Venue:X Space
Special Guest:@MissWRosa@woxiangni1997
🗓 May 15th 10 PM UTC+9
💰$100 #Giveaways👇
1️⃣Join the Bot :OneEarth Bot
2️⃣ Ask questions in Comment
3️⃣ Like & RT
Remember: One Earth, One Community! 🌎⚡️
✨ Giveaway: Creative Ways to Hide Your Tangem Wallet
🥳Our Discord Community Turns 1!
Celebrate with us by showing off your creativity in our special anniversary giveaway!
Are you a master of concealment? We’re challenging you to come up with the most fun hiding places for your Tangem Wallet. Whether it’s hidden in a book on your shelf or tucked behind a secret panel, we want to hear your best ideas!
🏆 5 Tangem branded Hoodies to be won on Discord in the #giveaways channel
👀 How to Enter:
Share your creative hiding spots in the #giveaways thread → top ideas, as voted by our community members, will win.
📅 Dates: Enter until the 28th June → 1st July we do a community vote → then we share the winners!
Cheers to the next year of the Tangem Community - to health, stealth, and wealth!
👾Join Discord and take part in contest →https://discord.com/invite/tangem
📰You can make your payment via @Premiumbot or Fragment to activate Giveaways
Currently, because this service is not ready, you'll receive ACCESS_DENIED message from the bot.
#Giveaways
👉The TG Times
📰Win Telegram Premium
By having all the conditions to receive Telegram Premium Gift from the channels, among the participants in this Giveaway, the desired number will be randomly selected to receive this gift.
After winning, a message containing the link to activate this subscription will be sent to you via Telegram.
You can also share this link with your friends so that they can get this subscription.
#Giveaways
👉The TG Times
📰New options for Giveaways
You can enable Additional Prizes if you want to give the winners your own prizes in addition to Premium subscription.
Also you can choose whether to make the list of winners public when the Giveaway ends.
#Giveaways | #Beta v.10.4
👉The TG Times
📰Giveaway Prizes
Giveaway Premium subscriptions to your channel members
Telegram is launching a new system to upgrade channels, where channel admins can create Premium Giveaways and set conditions such as location and date for them and boost their channels in this way.
This system is not yet fully available and can only be accessed on the test server.
Giveaway sources: @betawatch
#Giveaways | #Beta v.10.2
👉The TG Times
📰Giveaways are getting ready to be activated on the main server
Telegram beta configuration updates in each version make the Giveaways more complete and prepare for official presentation.
This system was active for some to receive more boosts from the first release of the beta version 10.2.0 on the test server.
Also, multiple boosts and the possibility of boosting more by giving a Premium gift are not activated on the main server, which can be related to the Giveaways.
It is expected that this system will be launched soon in the next updates for the main server.
Configurations by @tgcrawl
#Giveaways | #Configuration
👉The TG Times
Tonnel Network: New Measures Against Bot Farms in Giveaways
#giveaways#restrictions
Tonnel Network has enhanced measures to combat bot farms that manage to bypass restrictions in giveaways. Channel owners are encouraged to set at least one restriction to ensure the integrity of their free giveaways.
Source: link
@tonlines