Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🤝 Partnership: DejenDog X Pirate Frenzy
We’re super thrilled to announce our collaboration with DejenDog, a #Tap2Earn game based on Telegram and incubated by HashKeyWeb3. Hit to earn $HIT and get a chance to win additional $HSK.
They’re launching a 10 Million $HSK Airdrop campaign on DejenDog 🪂
️🎉 As the Official Airdrop channel for the $HSK program, DejenDog will offer our community an extra 300,000 $HIT per player.
👉 Head over to the DejenDog Mini App to claim yer eligible $HSK tokens:https://t.me/DejenDogBot?start=d02e7d44
👉 DejenDog Channel: https://t.me/DejenNews
- - -
Website | Twitter | TG Channel | TG Community | Discord
• Pirate Frenzy (Play-To-Airdrop Mini App on Telegram)
• Pirate Clash (Extension directly playable on Twitter)
🤝 Partnership: Mappasaurus X Pirate Frenzy
We are pleased to announce our collaboration with Mappasaurus, leveraging advanced AI and decentralized tech to develop a dynamic, constantly evolving global map.
🦖 Crackasaurus is their TON-based #Tap2Earn game where tapping earns you $CRACKA, the in-game currency. Climb the leagues to unlock unique NFTs with special benefits in the Mappasaurus ecosystem.
🤑Tap to Earn with Crackasaurus now: https://t.me/MappasaurusAppBot/Crackasaurus?startapp=piratefrenzybot
Check out for more details: https://x.com/PirateClash_HQ/status/1810730983471350090
- - -
Website | Twitter | TG Channel | TG Community | Discord
• Pirate Frenzy (Play-To-Airdrop Mini App on Telegram)
• Pirate Clash (Extension directly playable on Twitter)
New Listing OFFICIAL - $AVACN@avagoldcoin
🔹 Pair: AVACN/USDT
🔹 Deposit: Open NOW
🔹 Trading starts: July 30, 10:00 AM (UTC)
Join Bitgets #Tap2Earn $AVACN campaign to celebrate the listing!
Get a 5% daily boost on your deposit to #Bitget and earn $20 AVACN with a simple daily tap. 🚀
How to join?
☑️ Use the AVACOIN bot and complete #Bitget tasks: t.me/avagoldcoin_bot
👉 First sign up here: https://bonus.bitget.com/ALAA4W
👉 Then learn more here: https://www.bitget.com/events/tap-to-earn-more
🚀 Exciting Partnership Announcement!
We're thrilled to join forces with GPTWars, the first AAA game on ton blockchain!
Get ready to infiltrate, survive, and restore balance together. This marks a new era in gaming innovation and community engagement.
Stay tuned for more updates and epic adventures!
📲Join our awesome crew on Discord and stay updated on news: https://discord.gg/metafighter
Tweet 🔗:https://x.com/gametyio/status/1817096006208471440
Like, RT and comment the post to make some noise
📎Important Links:
Website | X | Chat | Discord | Announcement | Youtube
#tap2earn#play2earn
📢 Exciting Partnership Announcement!
We’re thrilled to announce that Gamety is now partnered with ElfinGames, the 1st GameFi Omni Layer focused on eSports! 👾
✨ Elfin Metaverse, backed by @BinanceLabs, is an all-in-one eSports gaming platform and open-world metaverse built on Elfin Lands, a virtual realm that offers a unique gaming experience and a thriving community!
🤝 Elfin Metaverse is joining the Gamety Fam with co-campaigns, AMAs and other fun community events.
📢 Stay tuned for any future updates on Gamety and the Elfin Lands.
Use Gamety unique invitation code: https://elfinmetaverse.com/?inviteCode=9XYZUC20 to earn more in Elfin Metaverse!
📲Join our awesome crew on Discord and stay updated on news: https://discord.gg/metafighter
Tweet 🔗:https://x.com/gametyio/status/1816761387005116529
Like, RT and comment the post to make some noise
📎Important Links:
Website | X | Chat | Discord | Announcement | Youtube
#tap2earn#play2earn
🔥 We've reached an incredible milestone of 100,000 Gamers in our#Tap2Earngame and the Fun's just starting 🚀
The best#Rewardsand#Opportunitiesare yet to come. Don’t miss out on this adventure.
🕹️Play#Crackasauruson @Telegram, invite your friends and earn$CRACKA, while shaping the future of mapping.
🦖 Dinos, Should we celebrate this with a#MEMEcontest where the funniest one wins?
🤑Join the Game here: @MappasaurusAppBot
𝕏 Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🪙1 DAY to $TOMA
The team announced decision to allocate 80% of entire $TOMA supply to community members😄😄😄
The team believes that the users should receive the majority share. After all, without users, there is no project — your support is what made #Tomarket possible.
A few key details to keep in mind over the next couple of days. Read them carefully:
✔️ The countdown ends October 31st at 23:59 HRS. Be sure you’re ready because this is when we’ll lock in your $TOMA allocation. Reach the highest level you can — every bit counts.
✔️ For accurate $TOMA allocations, the game will undergo a 24-hour maintenance period after the snapshot. Most features will go offline, giving us the time we need to finalize each allocation and remove any unwanted bots or bad actors.
✔️ Note that at this point, level upgrades, payment functions (TON stars, payments with #TON), and activity for $TOMATO or referral counts will be stopped.
✔️ You’ll be able to view your $TOMA balance after November 2nd 00:00 HRS (GMT+8).
$TOMA is seriously coming. And this is just the beginning.
See you in about 28 hours.
Tomarket Team
Those who have achieved at least🏅Gold + Medal Owner🎖 might find there's a little extra waiting for them...
The last call guys, LFG!!😄
#Airdrop#TGE#listing#BitgetWallet#Web3#TON#Tap2Earn
There's a lot to be made by tapping and claiming coins from the Go! Ton App!
Get started Here: https://t.me/thegoprojectBot
This bot is your free pass to Sweet rewards, get started Now.
Once you get started, you've got to maintain your spot as a weekly and monthly active user. Here's why:
🔹 There are more rewards as you get more active
🔹 You get features nobody else gets
🔹 You get into higher ranks which means exclusive airdrops will be sent to you.
🔹 You get access to collectibles reserved just for you
🔹 You get to Contribute more to the community, and influence the direction of the project
Ready to start Tapping?
Let's Go: https://t.me/thegoprojectBot
#gotonapp#tap2earn#bot#rewards#boost#wealth
Join: 🐣X✉️Chat✉️News🤖Discord
Play: 🕹️TON App💻Web App
Info: 🖥Newsletter🌐Website🌐Blog