Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
👀Educational content, charity and newcomer-friendly tools: An insightful look into the inner workings of a global crypto exchange.
🛡Learn how BingX diverse trading options can help you manage risks and capitalize on opportunities.
#DigitalCurrency
#Cryptonews
#CryptoCommunity
#Cryptolife
🚀 Iran Utilizes Cryptocurrency for Strait of Hormuz Passage Fees
Iran is employing cryptocurrency to collect fees from ships passing through the Strait of Hormuz. According to NS3.AI, TRM highlighted that the rapid nature of digital currency transactions and their operation outside the U.S. banking system complicate efforts by the U.S. to freeze or block these payments in real time.
#Iran#Cryptocurrency#StraitOfHormuz#DigitalCurrency#Shipping#USSanctions#Blockchain
Massachusetts to Establish Bitcoin Reserve
Massachusetts Senator Peter Durant proposes a bill to create a Strategic Bitcoin Reserve. This aligns with initiatives in states like Oklahoma, Wyoming, and Ohio, driving a potential federal reserve plan via executive orders or legislative action. Full details here: Blockspace
#Bitcoin#Crypto#Blockchain#Finance#Investment#Legislation#DigitalCurrency#Innovation#Massachusetts#UTC VC
🚀 Quantum Safe Bitcoin Proposed to Resist Quantum Attacks
Avihu Levy has introduced a concept called Quantum Safe Bitcoin, which is a hash-based transaction design intended to withstand quantum computing attacks. According to NS3.AI, this proposal seeks to enhance Bitcoin's security without altering its fundamental rules. The estimated cost for implementing this design using cloud GPU computing ranges from $75 to $150. However, the complete transaction assembly and broadcast have yet to be demonstrated on the blockchain.
#QuantumSafeBitcoin#Bitcoin#QuantumComputing#Blockchain#Cryptocurrency#CyberSecurity#DigitalCurrency#CryptoInnovation#BTC
🚀 AI TRENDS | Xverse Launches AI-Driven Bitcoin Wallet for Enhanced Transactions
Bitcoin wallet Xverse has announced the introduction of its AI-powered Agentic Wallet, designed to facilitate payments, transactions, and fund management on the Bitcoin network. According to Foresight News, the wallet utilizes Spark for lightning payments and supports machine-payable APIs through MPP, featuring a fully self-custodial architecture.
#AI#Bitcoin#Cryptocurrency#Fintech#Wallet#Blockchain#Payments#MachineLearning#DigitalCurrency#BTC
🚀 Solana Developer Platform Launches Amid Growing Interest in Stablecoin Settlement
The Solana Foundation has introduced its Solana Developer Platform, marking a significant milestone for the network as it reaches 167 million monthly token holders. According to NS3.AI, this development comes as major financial entities like Mastercard are investigating stablecoin settlement on the Solana blockchain. Additionally, Worldpay and Western Union are exploring on-chain settlement and cross-border transfer capabilities.
In a related move, MetaMask has announced that its MetaMask Card now allows American users to spend Solana USDC at any location where Mastercard is accepted. This expansion of services highlights the increasing integration of Solana's blockchain technology into mainstream financial systems.
#Solana#Blockchain#Stablecoin#Crypto#DeFi#MetaMask#USDC#Fintech#CrossBorderPayments#DigitalCurrency#SOL
🚀 Russia Implements Full Ban on Crypto-to-Cash Exchanges
Russia has enacted a comprehensive ban on crypto-to-cash exchanges, marking a significant policy development in the region. According to NS3.AI, this move is part of a broader trend of regulatory changes across Asia, as countries continue to refine their approaches to cryptocurrency regulation. The ban is expected to impact the way digital currencies are traded and used within Russia, potentially influencing other nations in the region to adopt similar measures. This development is one of several key policy shifts observed in Asia this week, highlighting the evolving landscape of cryptocurrency regulation.
#Russia#Cryptocurrency#CryptoRegulation#CryptoBan#DigitalCurrency#Asia#PolicyChange
Avalanche Visa Card Launches Today
Avalanche has officially launched its Visa card to promote cryptocurrency adoption. The card allows users to spend crypto easily in daily transactions, integrating DeFi solutions. This move aims to bridge the gap between traditional finance and the digital currency landscape, enhancing user accessibility to crypto assets. Read more here.
#Avalanche#Crypto#DeFi#Visa#Blockchain#Finance#MassAdoption#Payments#DigitalCurrency
🚀 Swiss Banks Launch Sandbox for Franc-Pegged Stablecoin Testing
Six Swiss banks, in collaboration with Swiss Stablecoin AG, have initiated a sandbox project for a stablecoin pegged to the Swiss franc, set to operate until 2026. According to NS3.AI, the test involves an ERC-20 token on the Ethereum blockchain and will be conducted in a controlled live environment with transaction limits and a restricted participant pool. While the specific access terms and use cases have not been disclosed, an interim report is anticipated in the second half of the year.
#Switzerland#Banks#Stablecoin#Cryptocurrency#Blockchain#Ethereum#FinTech#DigitalCurrency#Sandbox#Finance#ETH
🚀 Authorities Freeze $12 Million in Cryptocurrency Crime Proceeds
Authorities from the United States, the United Kingdom, and Canada have collaborated in a cross-border operation to freeze $12 million in proceeds from cryptocurrency-related crimes. According to NS3.AI, the investigation specifically targeted phishing schemes, highlighting the ongoing efforts to combat cybercrime in the digital currency sector.
#cryptocurrency#cybercrime#phishing#lawenforcement#crossborder#digitalcurrency#crimeproceeds#NS3AI