Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
EVAA Protocol: Temporary Suspension of stTON in Main Pool
#protocol#liquidity
EVAA has temporarily suspended the use of stTON as collateral in its Main Pool due to reduced market liquidity. Existing positions remain unaffected, but users must repay active loans before withdrawing stTON. The measure is temporary and will be lifted once liquidity conditions improve.
Source: link
@tonlines
🔤🔤🔤🔤🔤🔤🔤
Guys, some of you already heard about testnets, some of you not.
We would like to introduce you the first one called, Humanity protocol.
You need to claim your reward every 6 hours without clicking, entering combo and etc.
$RWT token is already trading.
Join humanity protocol👉link
#Testnet#Humanity#Protocol
DWF LABS makes another move to consolidate its position as one of the world’s leading Market Makers in #crypto, through a secondary investment in the MXC Foundation www.mxc.org - The MXC Foundation is the steward of the MXProtocol and the #MXC token. The MXC #token is listed on the world’s top exchanges, and starting on August 31st, MXC can be traded on Coinbase. DWF Labs made a multi-million dollars secondary market #investment in the MXC tokens and has been appointed as Market Maker.
#web3#marketmaking#protocol
🚀 StarkWare Researcher Proposes Complex Bitcoin Transaction Scheme
StarkWare researcher Avihu Mordechai Levy has introduced a Bitcoin transaction scheme that aims to circumvent the need for a protocol change. According to NS3.AI, the proposed method involves solving a pre-broadcast puzzle, which would necessitate approximately 70 trillion attempts. Levy characterized this design as a last-resort solution due to its significant computational demands, large transaction size, and potential relay-policy challenges, all of which could hinder scalability.
#StarkWare#Bitcoin#transaction#AvihuMordechaiLevy#protocol#computationaldemands#scalability#relaypolicy#BTC
Bitcoin Dominates Market with Huge Gains
Tesla's bitcoin holdings surge to $1.076 billion, boosting GAAP revenue by $600M. 🎉 The Sei Foundation launches a $65M fund for decentralized science startups, while GMCI unveils an index for US crypto protocols. Notably, Texas announces plans for a Bitcoin Reserve.
Read more about Tesla's valuation increase here. Explore the Sei Fund details here and GMCI's index here.
#Bitcoin#Tesla#DeSci#VC#Crypto#Funding#Texas#Cryptocurrency#Investment#MarketTrends#GMCI#Sei#Startups#Blockchain#Protocol#Accounting#Finance#Legislation#Innovation#CryptoProtocol
Ethereum Rollback Not Feasible, Developer Warns
Ethereum developer Tim Beiko cautions against rolling back the Bybit attack, citing potential widespread disruptions and significant costs exceeding $1.5 billion. This attack does not breach Ethereum protocol rules unlike the 2016 TheDAO incident. Additionally, a Bybit address transferred $48 million to Galaxy Digital and FalconX, acquiring 34,800 ETH shortly before depositing it back into Bybit.
Read more: Ethereum rollback debate and Bybit address transactions
#Ethereum#Bybit#Crypto#Blockchain#DeFi#News#Investment#ETH#GalaxyDigital#FalconX#TimBeiko#CZ#KanyeWest#Polychain#OTC#Transaction#Security#Protocol#Rollback#Market#Analysis
🚀 Polymarket to Upgrade Protocol and Launch pUSD Token on Polygon
Polymarket has announced plans to enhance its protocol and introduce pUSD, an ERC-20 collateral token on the Polygon network, fully backed by USDC. According to NS3.AI, the upgrade aims to lower gas costs and minimize failed trades. The platform intends to open-source the smart contracts next week and will initiate a bug bounty program to ensure security and reliability.
#Polymarket#Upgrade#Protocol#pUSD#ERC20#CollateralToken#Polygon#USDC#GasCosts#FailedTrades#OpenSource#SmartContracts#BugBounty#Security#Reliability
#java#bedrock#bedrock_edition#bedrock_to_java#bungee#fabric#geyser#geysermc#hacktoberfest#java#java_edition#minecraft#minecraft_bedrock_edition#packet#pe#protocol#proxy#spigot#translator#velocity
Geyser is a free tool that lets you play Minecraft across different versions by connecting Minecraft Java Edition servers. It works by translating data between the two game versions, enabling cross-platform play on devices like Windows, iOS, Android, and consoles. You can install it as a plugin or standalone, and it supports recent Minecraft versions. This means you can join Java servers even if you only have Bedrock Edition, expanding your multiplayer options without needing a separate Java account if you use the Floodgate plugin. It’s great for seamless crossplay but may have some minor limitations due to game differences[1][2][5].
https://github.com/GeyserMC/Geyser