Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🪂Don’t miss this, If you’re holding Ethereum
✅Final Phases of the Berachain Airdrop
🟠Berachain project has been in testnet for a year and is fundamentally a Layer 1 blockchain based on the EVM (similar to Polygon).
💰 raised $140 million from Tier 1 VCs to date.
🗓 Token to launch in Q1 2025, possibly in April 2025.
➡️🔝How to start:
🟢Step 1: Visit the following link:
🔗https://app.stakestone.io/u/vault/detail/bera
🟢Step 2: Connect your wallet and
💥 use this code for a 10% bonus:
69A92
🟢Step 3: If you have extra ETH, take advantage of this opportunity by adding liquidity on the StakeStone platform to maximize your chances of earning two airdrops:
- Berachain Airdrop
- StakeStone Airdrop
🟢Step 4: Deposit ETH, STONE, or WETH to receive beraSTONE tokens.
🔜 ETH withdrawals will be enabled soon, but when you deposit, you’ll receive equivalent beraSTONE tokens, which you can sell anytime on Uniswap to get your ETH back.
⬆️ Holding beraSTONE earns you project-related points for Dolomite_io and KodiakFi.
🪂Official rewards announced so far:
- $STO token rewards
- Berachain rewards via Boyco (a large portion of Bera tokens are allocated to Boyco, which means Berachain airdrop potential).
- Rewards from two projects: KodiakFi and Dolomite_io.
- Additional rewards to be announced.
#Berachain
🤝 Partnership: BearCage X Pirate Frenzy
Thrilled to announce our new partner, BeraCage, the first
Berachain Super Wallet on Telegram! They let users explore the #Berachain Testnet and discover the entire ecosystem right on Telegram.
Users can especially accumulate $BECA tokens by playing the Bear Hunting game, referring friends to BearCage, and much more. The more actions you complete, the greater your chances of earning $BECA and the Berachain token airdrop! 🪂
🐻 Join BearCage's Telegram Mini App now: https://t.me/bearcagebot/bearcage?startapp=nQcep_IflnIi
👉 For more details:https://x.com/PirateClash_HQ/status/1842162175894569068
- - -
Website | Twitter | TG Channel | TG Community | Discord
• Pirate Frenzy (Play-To-Airdrop Mini App on Telegram)
• Pirate Clash (Extension directly playable on Twitter)
Check Your $BERA On TokenPocket! 🐻⛓
Berachain Airdrop Checker is now live on TokenPocket’s Airdrop Zone, allowing you to verify your eligibility with just one click! 🎁🚀
📱https://tokenpocket.pro/en/download/app
💻https://tokenpocket.pro/en/dappstore?category_id=99998&category=Trend
#BERA#Berachain
🐻⛓ Q5! Berachain is now live on TokenPocket.
Berachain is a high-performance EVM-compatible blockchain built on Proof-of-Liquidity consensus.
💙How to create/import a Bera wallet on #TokenPocket?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/berachain
🎈Discover the #BERA Ecosystem with Your TokenPocket! #Berachain
📱https://tokenpocket.pro
💻https://extension.tokenpocket.pro
🐻⛓We now support users to add #Berachain Testnet “Artio” To their TokenPocket Wallet!
The Berachain is an EVM-equivalent L1 built on the Cosmos SDK and powered by Proof of Liquidity.
From now on, you can easily create&import&sync your wallet on berachain on TokenPocket Wallet!
👉https://tokenpocket.pro
#berachain_testnet
Berachain's Infrared Raises $14 Million
Berachain's liquid staking protocol, Infrared, successfully raised $14 million in a Series A token round. The funding aims to support its DeFi initiatives. Read more here: The Block
#DeFi#Berachain#Infrared#Crypto#Investments#Funding#VC
🚨 BREAKING: $117M in assets stolen from @Balancer in the last 2 hours after a major hack!!!
🔹 Assets stolen are across multiple chains: #Ethereum, #Base, #Optimism, #Sonic, #Polygon, #Berachain – mainly in Liquid Staking Tokens (LSTs) of $ETH.
Top 5 stolen assets:
• 7,838 $WETH (~$29.1M)
• 6,841 $OSETH (~$26.8M)
• 4,459 $WSTETH (~$20.1M)
• 2,405 $SFRXETH (~$10M)
• 2,038 $RSETH (~$8.67M)
🔹 The hacker is acting quickly: Converting LSTs into $ETH in real-time!
🔹 Big move: Whale account 0x009, dormant for 3 YEARS, just resurfaced after the exploit and withdrew $7.38M worth of assets from #Balancer!
⚠️ ALERT: If you’re still on #Balancer, secure your funds NOW before it’s too late! 🔐
Follow @spotonchain for more updates about the hack!
https://x.com/spotonchain/status/1985289043383300351
Utah Legislation on Bitcoin Investment Passes
🚀 The Utah House has passed legislation allowing state investment in Bitcoin, moving it to the Senate for further evaluation.
🔗 Read more about the implications of this bill here.
💸 Stablecoin donation company Coala Pay successfully closed a $3.5 million funding round.
🏦 Fed’s Christopher Waller supports stablecoins as vital for USD's reserve currency status.
✨ SEC is reviewing a Solana-ETF application from Grayscale.
📈 Developers of Berachain have launched their mainnet and conducted an airdrop.
🔒 Japan urges Apple and Google to block five crypto exchanges.
#Bitcoin#Stablecoin#CoalaPay#Fed#Stablecoins#SEC#Solana#Grayscale#Berachain#Japan#Crypto#Investment#Legislation#VC#News#USA#Fintech#CryptoExchange#DeFi#Funding#Innovation
Berachain Launches BERA Tokenomics Today
🐻 Berachain introduced BERA tokenomics with a total supply of 500 million tokens.
🐻 Distribution: 48% allocated to the community, including 15.8% for airdrop, 13.1% for future initiatives, and 20% for ecosystem development.
🐻 Eligible for airdrop: early testnet participants, NFT holders, liquidity providers, and Binance HODLers.
🐻 Mainnet launch coincides with the Token Generation Event (TGE) on February 6. More details can be found in ForkLog's article.
#Berachain#Tokenomics#Crypto#Airdrop#NFT#Blockchain#Mainnet#TGE#Community#LiquidityProviders#ETH#Bitcoin#ETF#Finance#Investment#DigitalEconomy#DAO#Kraken#Thailand#DEX