Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
📣The Nexus Wallet and Drop Hunter team announced the launch of a new project – Amabit!
📊 This is a trading broker terminal (all in one), which has strong partners: Binance, Bybit and OKX, 300+ cryptocurrencies are currently available for trading.
Tools of the new crypto platform #Amabit:
🟨 Trading on top exchanges
🟨 Ability to connect to trading bots
🟨 Wealth and portfolio management
🟨 Investing in #DeFi
🔥Drop Hunter is slowly transforming into #superapp, which will have the functionality of an exchange, a wallet and a gamified platform for #airdrop.
❤️ In addition, Nexus Wallet also had a big update, adding:
🟨 DEX exchanges
🟨 NFT support
🟨 Simplified withdrawal of funds
🟨 P2P market
🟨 QR NFT and wallet security improvements
🩹 Now there are some technical problems with the game Drop Hunter, but next week the team plans to restart the farming function and fix all the bugs, so we are waiting.
Game | Chat | Channel | YouTube | Nexus
☕️Drop Hunter is launching another airdrop, but this time with #Amabit
📊 Amabit is an all-in-one brokerage trading terminal from the Drop Hunter team, which has strong partners: #Binance, #Bybit and #OKX, 300+ cryptocurrencies are currently available for trading, more details here.
💰 A total of 2,000,000 $DROP coins will be distributed between all participants, compared to the airdrop from #Bybit, twice as many tokens, the rewards for each participant have been increased by 4 times, while the number of winners has been reduced by 2 times.
The requirements for participation are below:
🟡Launch the bot.
🟡Register on Amabit and complete KYC.
🟡Join the Amabit chat and send a screenshot showing that KYC is completed.
🟡Invite 5 friends (old referrals count).
🟡Buy 1 ticket and wait for the results to be announced.
📇 Additional information for participants – you get 20% of the winning ticket of your friend you invited. This means that if you invited 10 people and they won at least 1 ticket, you will receive 40 #DROP tokens from each ticket.
🟡Drop type – Raffle.
🟡Total volume – 2,000,000 $DROP.
🟡Total winners – 10,000 people.
🟡For each user 200 $DROP for 1 ticket (20,000 points = 1 ticket).
🔥 We remind you that the #DropHunter team is planning a token listing on a major exchange in the fall, so we continue to farm and participate in all their airdrops.
Game | Chat | Channel | YouTube | Nexus
💰Drop Hunter launched the first airdrop in $DROP token!
🎟 In #airdrops tab, it is now possible to exchange farmed coins for tickets, which increase the chances of receiving their $DROP token.
The conditions are as usual simple:
🟨Log into the bot and go to the "airdrops" tab
🟨 Invite 3 friends and subscribe to the desired channels
🟨 Exchange collected coins for tickets
🟨 Wait for the end and check the internal wallet
🚀 Let us remind you that, according to the team, $DROP is a utility token of the ecosystem, which includes the projects: #Amabit, #DropHunter and #NexusWallet. It will be used to pay for internal services.
💎Rewards: 500K out of 8M total supply.
🟡 Drop type – raffle
🟡 Total winners – 3300 people
🟡 $DROP for each winner
🔥 Closer to autumn, the team is planning to list the #DROP token on a major exchange, so let's continue to farm and participate in all their airdrops.
Game | Chat | Channel | YouTube | Nexus