Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Arthur Hayes (@CryptoHayes) just unstaked and deposited 7.9M $ENA ($6.44M) to #Binance and #Bybit as the price dropped 9% in the past 24 hours.
He previously accumulated 16.79M $ENA at ~$0.666 ($11.19M) in late Nov 2024 and staked them for rewards.
To date, he has deposited 16.9M $ENA back to CEXs at ~$1.01 ($17M), likely earning $5.52M (+48%).
Follow @spotonchain and check out the #ArthurHayes entity via https://platform.spotonchain.ai/en/platform/entity/1552
🚨 Arthur Hayes just dumped nearly $5M in crypto!
Sold ETH, ENA, LDO, AAVE, UNI, and ETHFI in 24 hours. Looks like he's cashing out! 💸
#ArthurHayes#CryptoNews
🚀 Arthur Hayes: AI to Enhance Institutional Trading Dominance Over Retail Investors
Arthur Hayes has expressed that artificial intelligence will enable institutional trading systems to surpass retail traders in direct market competition. According to NS3.AI, Hayes advised retail investors to steer clear of short-term speculation and instead focus on holding cryptocurrencies for the long term.
#ArthurHayes#AI#InstitutionalTrading#RetailInvestors#Cryptocurrency#LongTermInvesting#NS3AI#MarketCompetition
🚀 Arthur Hayes Increases HYPE Holdings After Three-Month Hiatus
Arthur Hayes has made a significant move in the cryptocurrency market by purchasing 26,022 HYPE tokens, valued at approximately $1.1 million, after a nearly three-month break. According to BlockBeats, this acquisition brings his total holdings to 247,334 HYPE tokens, worth around $10.44 million, with an unrealized profit exceeding $2.5 million.
#ArthurHayes#HYPEHoldings#Cryptocurrency#CryptoMarket#BlockBeats#CryptoInvestment#HYPETokens#UnrealizedProfit
🚀 Arthur Hayes Skeptical of Iran's Alleged Bitcoin Toll Collection
Arthur Hayes expressed skepticism about Iran's purported acceptance of Bitcoin for toll payments on April 9. According to BlockBeats, Hayes stated that he would only believe Iran is collecting tolls in Bitcoin if he sees actual transactions on the Bitcoin blockchain. Otherwise, he considers it a tactic by the Islamic Revolutionary Guard Corps to mock the Western fiat currency financial system.
#ArthurHayes#Iran#Bitcoin#TollPayments#Blockchain#Cryptocurrency#IslamicRevolutionaryGuardCorps#FiatCurrency#FinancialSystem#BTC
Ethereum Rollback Proposed After Bybit Hack
Arthur Hayes proposes rolling back Ethereum to a block prior to the $1.5B Bybit hack, arguing it would benefit both the platform and holders. He asserts that Ethereum’s immutability can be revisited, citing prior instances. Support for the rollback comes from Bitcoin maximalist Samson Mow, suggesting it could limit funding for North Korea’s nuclear program. The plan involves pausing all ETH trading and renaming the hacked chain to ETHNK. Bybit CEO assures that company assets exceed the lost amount, with significant reserves remaining secure. For details, read more here.
#Ethereum#Bybit#Crypto#Blockchain#Security#Hack#SamsonMow#ArthurHayes#ETH#VC#LazarusGroup#NorthKorea#Defi#Investing#Market#Trading#USDT#WhaleAlert
🚀 Arthur Hayes Warns of Potential Federal Reserve Intervention in Private Credit Market
Arthur Hayes has highlighted concerns regarding the approximately $1.8 trillion private credit market, suggesting that stress within this sector could necessitate a liquidity intervention by the Federal Reserve. According to NS3.AI, Hayes noted that regulators are currently scrutinizing the exposure of banks and insurance companies as the sector faces rising redemptions and an increase in non-performing loans.
#ArthurHayes#FederalReserve#PrivateCredit#LiquidityCrisis#Banking#Finance#NonPerformingLoans#CreditMarket#Regulation
BTC & ETH ETFs See Massive Inflows
🎄Christmas Update on Crypto ETFs! BTC ETFs had an inflow of $978.6 million, while ETH ETFs attracted $128.7 million. Ex-BitMEX head Arthur Hayes predicts the bullish phase may peak by mid-March, suggesting to increase risk but take profits before April due to upcoming tax and liquidity tightening cycles. Positive dollar momentum is expected to boost liquidity by $612 billion. Key drivers include a decrease in RRP funds and TGA usage by the U.S. Treasury. 🚀
For more details, visit: Wu Blockchain News
#Crypto#BTC#ETH#ETF#ArthurHayes#MarketTrends#Liquidity#RRP#TGA#QuantitativeTightening#Finance#Investing#BullMarket#CryptoNews#MarketPredictions#Inflows#Christmas2025#LiquidityDrivers
Ethereum ETF Sees Major Inflows
The Ethereum spot ETF recorded a net inflow of $139M last week, with Blackrock's Ethereum ETF, ETHA, gaining $135M. However, on January 27, the crypto market saw declines across sectors, with DeFAI down 28.73%. Other sectors like AI Agents saw a 16.91% drop. U.S. crypto czar David Sacks noted ongoing evaluations regarding Bitcoin and digital assets. Meanwhile, Rosseti, Russia's state power company, plans to introduce Bitcoin mining to leverage idle power resources. Runetoshi's new memecoin, Runes, faced volatility, dropping from $28M to $500k in market value. Arthur Hayes predicts Bitcoin could dip to $70,000 before a future rise to $250,000 this year. More on ETF inflows | Market drop details | David Sacks comments | Rosseti's Bitcoin mining | Runes token collapse | Hayes Bitcoin predictions
#Ethereum#ETF#Crypto#Bitcoin#Russia#Mining#Securities#Stablecoins#PricePrediction#DigitalAssets#Memecoin#MarketDrop#Runetoshi#DeFi#AI#QuantitativeEasing#USDC#WhaleAlert#MarketVolatility#FinancialCrisis#ArthurHayes