TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 82 слични објави

Пребарај: #evaa

当前筛选 #evaa清除筛选
Binance crypto champions

@binancecryptochampions · Post #2964 · 20.12.2025 г., 12:41

✴️Free signal-Futures ✴️ ⚡️⚡️#EVAA/USDT⚡️⚡️ Signal Type: Regular (Long) Leverage: Cross (20x) Margin: 2.0% Entry Targets: 1) 0.775 2) 0.855 Take-Profit Targets: 1) 0.91 2) 0.95 3) 1.03 Stop Targets: 1) 0.735 🍁 Published by: @Trading_exp🍁 Join_vip: @Crypto_Futures_Spot_Payment_bot

Hashtags

Binance crypto champions

@binancecryptochampions · Post #2785 · 16.10.2025 г., 02:19

✴️Free signal-Futures ✴️ ⚡️⚡️#EVAA/USDT⚡️⚡️ Signal Type: Regular (Long) Leverage: Cross 20.0x 🚪Entry Targets: 1) 2.82 🎯Take-Profit Targets: 1) 2.895 2) 3.033 3) 3.38 🚫Stop Loss: 2.657 🌱 Published By: @Trading_exp🌱 Join_vip: @Crypto_Futures_Spot_Payment_bot

Hashtags

🎆 The long-awaited 😇 EVAA TGE is just around the corner! And FIVA is now live in closed mainnet 👍 FIVA Protocol is one of the most advanced DeFi projects on TON right now. Think of it like Pendle on Ethereum, but built for TON: users can lock in fixed yields, trade future yield, and treat yield as a tradable asset. 💡How does it work? Let’s say there’s 100 USDT and the goal is to lock in 5% APY over 60 days • Open FIVA in Telegram and connect a wallet • Under the Earn tab, convert 100 USDT into a PT (Principal Token) — a base asset that returns with a fixed 5% • In the Market tab, buy or sell YT (Yield Token) — a token representing rights to the future yield To simplify: PT — fixed base + guaranteed return YT — tradable yield — can be held or sold for potential profit 💵 Funds can be withdrawn early, but the outcome will depend on market conditions. Both profits and losses are possible. 💻FIVA is currently live in closed mainnet. Liquidity is still limited, so large positions may cause slippage. But: 🟠 $EVAA $XP can be farmed 58x faster with YT 🟠 Yield, XP, and trading fees are available via liquidity pools 🟠 Everything is explained in the official strategy guide 🛡 FIVA has already been audited, integrates Pyth oracles, and remains protected even if #EVAA encounters issues — fixed yields stay intact. 😇And finallyyy…🥳🎉🎆TGE news is here!!! The official TGE page has gone live with the first details. Vesting and token lock specifics are still being finalized — more updates expected soon. FIVA App | Channel

Hashtags

EVAA integration in Binance Web3, joint activity with Storm Trade and boosts for XP farming 🏦 Binance Web3 Wallet has integrated EVAA — its good news, now onboarding new users in TON DeFi, exactly in #EVAA, will be easier and faster.💱Last year, the OKX exchange also integrated EVAA in its Web3 wallet. 🪙 EVAA and Storm Trade are giving away 2 000 000 RP for liquidity supply. The reward will get only top 20 suppliers, your part of reward will depend on the supply amount and the time spent in the pool. You need to hold until 03/03/2025. 🔥 Increasing the coefficients for EVAA XP farming. The NFT card boost rate has been increased from 1.1x to 1.2x, and for your referrals from 5% to 10%. The maximum bonus is now ~1.73x with Boost Card, Mainnet Card and Telegram Gifts. 😇EVAA also took 9th place in the CryptoRank rating – 15 best projects by TVL growth in January 2025. EVAA app | News | Chat | Website

Hashtags

Getting ready for EVAA XP halving⬇️ Very soon, the number of #EVAA XP points received will be halved, which will increase their value, respectively, and the future token too. 🟣 Season 1: will last until June 24, the first halving will occur. 🟣 Season 2: from June 24 to August 1, after which there is also a halving. 🟣 Season 3: Starts August 1st until TGE. ✅ Therefore, we are not relaxing, but rather accelerating the pace and continuing to actively farm XP, because $EVAA promises to be a promising coin and we expect its release at the end of this summer. 🔽We would also like to remind you of several activities from EVAA that are worth taking part in: 💥EVAA and TonStakers (more details in the previous post ) 💥EVAA and Bemo (more information here ) 💥Evaa, @Xircus and @XPlus (our previous post about this ) EVAA app | News | Chat | Website

Hashtags

123•••67
ПретходнаСтраница 1 од 7Следна