Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🥊 Listing $DFC on Bitget — is it worth buying a token?
$DFC is the main token of the Definer ecosystem on the TON blockchain with more than 100 services on one platform. At the moment, the project has the largest community on the blockchain — more than 450k people, and the token itself is trading at a price of $3.14 on MEXC, is in the top projects on TVL and in the top 500 projects on CoinMarketCap.
Often, at the start of the listing, you can catch the best entry point and pick up the icons in the future.
🔍 Several reasons why you should look at buying $DFC:
1. The $DFC token is listed on MEXC and added to the telegram @wallet wallet. This means that new users coming to the $TON ecosystem see it. And this gives an even greater boost to the price and potential x's.
2. More than 25,000 active DFC wallets. The distribution of DFC on holders' wallets indicates the interest of whales.
3. The project and the token have direct support from $TON, Binance Labs and #DWF, the largest players in the ecosystem pumping market.
4. Capitalization is only $ 80 million, there is room to grow, cap #PEPE is $ 3 billion.
In addition, the Token2049 conference is approaching, where Durov will speak. This means that $TON and all the projects around it will get a big boost.🔥
Bidask Protocol — New DEX on TONand a Giveaway💵33,000
🅱️Bidask launched in mainnet just a few days ago — before that, the exchange was in the testnet for almost three months. The team claims that their swap model is faster, cheaper and more efficient than its analogues. Practice confirms: exchanges are instantaneous, and the 10-15 sec delay is just the time it takes for the wallet to pick up the transaction. Further optimization is already on the TonCore side.
💰The seed investor is DWF Labs (market maker and validator #TON). For a young project, this is a serious resource — #DWF is building its own ecosystem and strengthening the platforms it is a part of.
#Bidask — partner 🌑#TONFest. The festival will feature a raffle 💵 33,000, and you only need to complete three tasks:
✔️Make $10 swaps
✔️Provide $10 to liquidity pools
✔️Provide $20 to liquidity pools (first $10 does not count). Your $20 is locked in the pool until June 30, 2025.
We recommend the $TON/$USDT pairand be sure to follow the buttons inside TON Fest — otherwise the quest will not be counted.
Bidask DEX | Channel
🚀 DWF Labs Founder Predicts Older Coins Unlikely to Reach All-Time Highs
DWF Labs founder Andrei Grachev has expressed skepticism about the potential for older cryptocurrencies to achieve their previous all-time highs. According to NS3.AI, Grachev noted that while the market dynamics have evolved, many of these older projects have not adapted accordingly. This observation suggests a challenging future for legacy cryptocurrencies in the rapidly changing digital asset landscape.
#DWF Labs #Andrei Grachev #cryptocurrencies#all-time highs #NS3.AI #legacy cryptocurrencies #digital assets
The first HACK-A-TON by The Open Network (TON) in South Korea has just started! 🔥
Super excited to be one of their main sponsors 🚀🫡
Pop by to meet up with us, or any rep from BoomLabs, Ozys, and TAV (The Open Network, Alphanonce, VistaLabs).
Address: B1, 126, Teheran-ro, Gangnam-gu, Seoul, Republic of Korea
주소: 서울 강남구 테헤란로 126 B1 수호아이오
KR page: https://lnkd.in/g9e-eDtb
EN page: https://lnkd.in/gpsPXMWG
#dwf#TheOpenNetwork#TON#Telegram#Hackathon#Seoul#Boomlabs#Ozys#TAV#Alphanonce#Vistalabs
🚀 Market Conditions Present Opportunities for Strategic Investments, Says DWF Labs Co-Founder
The cryptocurrency market is currently experiencing a "very boring" phase, according to ChainCatcher. DWF Labs Co-Founder Andrei Grachev expressed on social media that while participants may engage in discussions or humor, significant activities such as financing, trading, investing, and business expansion are quietly underway.
Grachev noted that the current market environment poses challenges for major projects, exchanges, and companies to make new listings or significant announcements, as high-profile actions may not be effective at this time. He advised maintaining patience in investment portfolios and waiting for more opportune moments.
He emphasized that the market is not in decline but rather offers opportunities for seemingly mundane activities, such as buying and holding Bitcoin long-term or engaging in altcoin speculation. Grachev concluded that there is still much to do for builders and investors, while smaller investors should focus on learning, avoid lamenting losses, and enjoy the market they have chosen to enter.
#cryptocurrency#marketconditions#investmentopportunities#DWF Labs #AndreiGrachev#bitcoin#altcoin#longtermholding#speculation#investors#builders#patience#learning#BTC
DuckChain Secures $5M Funding
TON’s consumer layer for Web3 DuckChain has successfully raised $5 million in a funding round with participation from multiple investors including dao5, Offchain Labs, DWF Ventures, and others.
#DuckChain#Web3#Funding#TON#dao5#OffchainLabs#DWF#Investors#Ventures#Kenetic#Skyland#GeekCartel#GateLabs#PrestoLabs#Camelot#Quantstamp#Blockchain#Finance#Investment#Technology