Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of September 2022.
Download depo-REPORTER No 13 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
deponet.uz|Tg|Fb|Inst|Youtube
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of August 2022.
Download depo-REPORTER No 12 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
www.deponet.uz|Tg|Fb|Inst|Youtube
BitMEX Seeks Buyer with Investment Bank Help
BitMEX, a prominent cryptocurrency exchange, is actively looking for a buyer and has engaged Broadhaven Capital Partners for assistance. Founded in 2014 by Arthur Hayes, BitMEX faced legal challenges in the U.S. concerning anti-money laundering protocols, leading to Hayes' resignation as CEO. For more details, read here.
#BitMEX#Crypto#VC#Blockchain#Exchange#Investment#FinTech#AML#Securities#Trading#Cryptocurrency
U.S. Releases Seized Crypto Mining Machines
U.S. authorities begin releasing seized Chinese-made cryptocurrency mining machines, totaling up to 10,000 units at various ports. Synteq Digital's CEO notes resistance from some CBP officials towards Bitcoin mining, hindering the industry's growth.
🔗Read more
In related news, BioNexus Gene Lab approves Ethereum as its treasury asset; Bitcoin open interest reaches lowest since August; and Bitwise files for Aptos ETF.
🔗BioNexus News
🔗Bitcoin Open Interest
🔗Bitwise Filing
#Crypto#Bitcoin#Ethereum#Mining#BioNexus#Aptos#ETF#VC#Blockchain#Finance#Investment#DeFi#Securities#Regulation#Innovation#MarketTrends#OpenInterest#USeconomy
Milei Withdraws LIBRA Support Amid Cash Out
Argentinian President Javier Milei retracts his endorsement of $LIBRA after insiders reportedly cashed out $107 million. The move raises questions about transparency and the impact on the cryptocurrency's reputation. For more details, visit The Block.
#Argentina#Milei#LIBRA#Crypto#DeFi#Blockchain#Investment#Transparency#Finance#Market#News#Updates#Economy#InsiderTrading#Regulation#Securities#Volatility#Trends#DigitalCurrency#Cryptocurrency
Major Updates on Bitcoin and Ethereum
🔗 *Roman Storm secures legal funding for trial* with support from Paradigm and Vitalik Buterin! Details here: Leviathan News.
🔗 David Sacks confirmed evaluating a *national Bitcoin reserve* is a priority for Trump's Digital Assets Task Force. BTC is touted a *superior store of value*. Regulations on crypto incoming within six months!
🔗 XRP Ledger briefly halted due to validation issues but self-healed. More info: Coindesk.
🔗 Hong Kong weighs *Bitcoin as a strategic reserve*, urging to accelerate feasibility studies. Insights here: Wu Blockchain News.
🔗 Ethereum's *supply rises* back to pre-merge levels due to Dencun upgrade, signaling inflation. More: The Block.
🔗 U.S. to consider Bitcoin reserve as an essential economic security asset; institutional adoption underway!
#Bitcoin#BTC#Ethereum#ETH#Crypto#Legal#Funding#XRP#Regulations#HongKong#StrategicReserve#DigitalAssets#AI#VC#MicroStrategy#Inflation#Securities#DeFi#Stocks#Bonds#ETFs
Tokenized Mining Notes Coming to El Salvador
Bitfinex Securities to launch Blockstream Mining Note 2 (BMN2) in Q1 2025. BMN2 offers returns based on bitcoin mined by Blockstream. Previous note (BMN1) delivered over 1,212 BTC to investors in three years. More details in the article here: Read more
#Bitfinex#Blockstream#BMN2#ElSalvador#Bitcoin#Crypto#Investment#Tokenization#Mining#BTC#Finance#DeFi#DigitalAssets#Securities#Blockchain#Trading#Market#Returns#BMN1#Innovation#Economy
Metaplanet Plans $745M Bitcoin Purchase
Tokyo-listed Metaplanet aims to raise ¥116 billion (approx. $745M) through 21 million share subscriptions at 0% discount for Bitcoin acquisitions. This represents one of the largest financing plans for Bitcoin by any Asian publicly traded company. Detailed info available here: link. Meanwhile, U.S. Bitcoin and Ethereum ETFs received $1.9B in inflows during Trump's first week, bringing total digital asset inflows for 2025 to $4.8B. U.S. Senate also confirmed pro-crypto Scott Bessent as Treasury Secretary, expected to influence crypto regulations amid heightened interest.
#Bitcoin#ETF#Crypto#Investment#Metaplanet#Asia#Treasury#DigitalAssets#BTC#ETH#Finance#NASDAQ#WallStreet#MarketTrends#Inflows#Securities#Cryptocurrency#USeconomy#Regulations#Trump#ProCrypto
Argentina's Opposition Eyes Impeachment Over LIBRA
Argentina's opposition is considering impeachment for President Milei after conflicting support for the LIBRA token. This follows a controversial launch that saw rapid investment and then a significant drop in value, leading to accusations of mismanagement and deception. The situation raises questions about political influence in cryptocurrency projects.
Read more: Reuters
#Argentina#LIBRA#Crypto#Impeachment#Milei#Investment#MarketManipulation#EconomicCrisis#Blockchain#DeFi#RugPull#Politics#Cryptocurrency#TokenLaunch#InsiderTrading#Securities#AI#VC
Thai SEC Considers Bitcoin ETF Approval
The Thai Securities and Exchange Commission is evaluating a proposal to approve a Bitcoin ETF for listing on its local exchange. Currently, Thai investors can only access overseas Bitcoin ETFs through a fund of funds product launched in mid-2024. Read more
#Thailand#Bitcoin#ETF#Crypto#Investing#Finance#USDC#fxUSD#XRP#WhaleAlert#Assets#Trading#Decentralized#Yield#Securities#Exchange#LocalMarket#DigitalAssets#BlueChip#Stablecoin#VC
Trump Establishes Strategic Bitcoin Reserve
Former President Trump has signed an order to create a strategic Bitcoin reserve in the U.S., based on approximately 200,000 BTC confiscated by the government. This reserve will serve as a savings asset, not intended for sale, acting as a digital Fort Knox. Meanwhile, analysts indicate that governments may follow the U.S. lead, reducing the likelihood of Bitcoin bans from regulators. Post-announcement, Bitcoin saw a price drop from $91,000 to $85,000 but has since recovered to $88,000. No altcoins are currently included in the reserve plans. Full details here: Reuters
#Bitcoin#crypto#Trumpr#US#Blockchain#Finance#Regulation#Assets#DigitalCurrency#Investments#Savings#Market#Trading#Reserves#Government#FTX#Securities#FortKnox#Economy#PriceDrop#StrategicReserve