Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
DAOLama x CapsGame: Launch of 'Follow the Lama' Season
#DAOLama#CapsGame
The DAOLama NFT Lending (@daolama) channel announces its collaboration with CapsGame for the launch of the 'Follow the Lama' season. Players can now use DIAMOND chips as collateral to gain liquidity on the DAOLama App. The new season features exclusive tasks, a leaderboard, and rewards that include converting lama points into tickets for valuable in-game items.
Source: link
@tonlines
👊Fatality Package is live
The arena burns with fire and lava – the atmosphere of an epic battle returns with the new ❤️CapsGame collection!
🔥 Total supply – 690,000 caps
🔥 Available in all packs: from Common to Legend
🔥 Each cap is a piece of the legendary universe, ready to become a weapon in your collection
Collect, trade, and fight – the collection is already waiting for you!
#CapsGame#TON#NFT#GameFi
🥴Whoaa! Chip utility is live, and farming has officially begun!
Astrologers have announced a month of major updates in #CapsGame. Did you think that chips were just for fun? No, they are not. Now chips can be sent to ❇️ staking and receive CapsGame tokens for them.
❤️$СG Token
🟣 The first phase of farming starts today and will last 10 weeks, during which we will distribute 5% of the total token supply.
🟣 Starting today, 30% of purchases will be sent to the liquidity pool at capsgame-liquidity.ton.
🟣 This is just the beginning, there will be a lot of news and updates in the game over the next 10 weeks. Don't miss out!
📝How does staking work?
Where the profile used to be, now lives a new beast called "Token". Let's figure out what that means:
➡️ You have 9 slots available for staking: 6 slots for chips of any collections, and 3 slots only for certain collections, which will change once a week, at 00:00 Moscow time on Wednesdays.
➡️ Each staked token generates a certain amount of tokens per hour (starting with EPIC).
➡️ The higher the grade and popularity of the feature, the higher the generation speed.
➡️ The higher the grade of the chip collection that is staked, the greater the bonus to the generation speed!
Still confused? Hit the wiki for the full breakdown
Game | Wiki | Chat | NFT collection
#CapsGame#TON#NFT#GameFi
Festival season with Ton Festival and CapsGame!
Our friends from ❤️CapsGame and
🔠TON Festival decided to join forces and launch a new season! A festive atmosphere, fresh activities, and, of course, a bunch of surprises — all this is already here!
What's ahead?
⚫️6 Cool Chips for Your Collection
⚫️ Huge edition — 20,000 chips
⚫️ Leaderboards and festival activities right in the game!
How to Earn you Tent Points 🏕
⚫️ Completing dailies: 10
⚫️ Mint of any chip: 50
⚫️ Chip Madness Round Completion: 5 (no repeats)
⚫️ Upgrade your chips to Legend+ and higher — the cooler the chip, the more points!
🏅Prize fund — tickets🎫 giving cool bonuses and exclusive items await those who collect the most points at the end of the season.
🗓️The final day of the event is March 27. The store opens on March 28th — exchange tickets for cool prizes!
🫶Become a part of the main event of the year!
#CapsGame#TONFest#Web3#TON
CapsGameon💎TON Community
The game was mentioned on the official TON channel, perhaps a hint that it is a future participant of the League.
CapsGame combines nostalgic gaming with innovative Web3 technologies, incentivizing active participation in the TON ecosystem through NFT trading. Players can earn rewards and profits from trading and upgrading their NFTs.
The game offers a PvP mode for those who like to take risks and bet their NFTs on the outcome of a battle with other players, as well as a safe PvE mode in which the player trains by playing with bots. CapsGame also encourages engagement and competition through rankings and quests.
And right now there is a new contest in BroBot together with #CapsGame in which you can get a unique SBT BroBot CapsGame and other prizes absolutely free.
☀️Complete tasks and get SBT!
#NFT#SBT#TON#BroBot
🛋Ease In, Get Cozy, Enjoy
❤️CapsGame has become even more cozy — the team has updated the main screen! Now the mini-app has become even more cozy and addictive. No more associations with clickers — maximum nostalgia for the OG game Chupa Caps, so launch the game and immerse yourself in the atmosphere of childhood.
Collect your favorite chips and turn valuable items into NFTs, which are already traded on #Getgems.
Game | Wiki | Chat | NFT collection
#CapsGame#TON#NFT#GameFi
💎CapsGame is launched! Caps are back from the 90s!
🧑💻CapsGame finished beta testing, fixed bugs and improved the app itself. Added in-game purchases for stars, plans to add support for payment in $TON and new activities based on the rating table
👌 The public release introduced a leaderboard that will be formed based on unique player collections. This means that each chip you collect will earn you points. By upgrading chips or completing collections, you will earn additional points. Each chip will be unique, with its own number, and collections will be strictly limited. More details.
🙂 For active participants of the beta test, special rewards were provided, which you can read about in this post.
Play in our Yard and start collecting rare chips, let's try to rise in the district rating together!😎
1️⃣Go to bot
2️⃣ Come into our yard
3️⃣ Play and win!
#CapsGame#TON#NFT#GameFi#ChildhoodComingBack