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

Резултати

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

Пребарај: #daolama

当前筛选 #daolama清除筛选
TONlines – News

@tonlines · Post #7375 · 26.05.2025 г., 13:26

⚡️DAOLama NFT Lending: APY Increased to 3.64% #TON#DAOLama DAOLama NFT Lending announces an increased APY of 3.64% for their vault, offering higher yields for TON holders. With current liquidity being utilized efficiently, the deposit limit is set at 150,000 TON. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7311 · 21.05.2025 г., 15:07

DAOLama NFT Lending: Deposit Reopening in DAOLama Vault #DAOLama#TON DAOLama NFT Lending announces the reopening of deposits in the DAOLama Vault. With almost 100% utility reached, the channel invites users to take advantage of the new 150,000 TON limit and growing APY ahead of upcoming events. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7258 · 18.05.2025 г., 09:06

⚡️DAOLama NFT Lending: Buy TG Stars and Premium with TON #TON#DAOLama DAOLama NFT Lending has introduced the option to purchase TG Stars and TG Premium using TON directly within the DAOLama App. This update simplifies purchases, eliminating KYC requirements and supporting USDT in the next update. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6947 · 28.04.2025 г., 16:21

⚡️DAOLama: Final Days of Anonymous Telegram Numbers Contest #Telegram#DAOLama DAOLama announces that there are only three days left until the end of the Anonymous Telegram Numbers Contest. Participants are reminded of the special annual interest rate of 10% on loans available until the event concludes. Partners provide additional offers to boost points. Source: link @tonlines

TONlines – News

@tonlines · Post #7419 · 28.05.2025 г., 14:21

DAOLama NFT Lending: Activate Your SBT Discounts #DAOLama#SBT The DAOLama NFT Lending channel announces the activation of discounts for SBT Tier-1, Tier-2, and Tier-3 tokens. Users can use the DAOLama App to claim their discounts and apply them to loans with Anonymous Numbers. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7100 · 08.05.2025 г., 10:08

DAOLama x CapsGame: Launch of 'Follow the Lama' Season #DAOLama#CapsGame The DAOLama NFT Lending (@daolama) channel announces its collaboration with CapsGame for the launch of the 'Follow the Lama' season. Players can now use DIAMOND chips as collateral to gain liquidity on the DAOLama App. The new season features exclusive tasks, a leaderboard, and rewards that include converting lama points into tickets for valuable in-game items. Source: link @tonlines

🦙DAOLama Team x TON Society Event! This month is set to be special for all Telegram Anonymous Numbers holders 🐶 Together with TON Society and leading DeFi partners, the DAOLama team has prepared a massive event that will grant number holders exclusive opportunities and benefits within the TON ecosystem 🤟 🏆Prizes & Rewards 🥇Zero-fee liquidity 🥈50% discount on fees 🥉25% discount on fees 🐷SBT & Lifetime Bonuses 🏆Top-10 – 10% discount 💎 Top-50 – 7% discount 💎 All participants – 5% discount 🪙Upgraded Benefits: 🟢Enjoy a reduced 10% interest rate (only during the event). 🟢Extended loan period of up to 2 months. How to participate? ✅ Prepare a wallet with your Telegram Anonymous Numbers NFT ✅Take a loan on DAOLama and use TON in DeFi projects ✅ Track your position on the Leaderboardand accumulate points Bonus Points from Partners 🤝Tradoor – 0.25 points per TON provided 🤝Ston.fi – 0.25 points per TON provided 🤝Rainbow.ag – 0.25 points per TON exchanged 🗓️The contest is live – don’t miss your chance! 🦙Join DAOLama now! #DAOLama#SBT#DeFi#TONSociety

🪅DaoLama launched vault in TON with APY 40% and announced the $LLAMA holder incentive program ❤️ A function has appeared to provide liquidity in the TON token, where 80% of the income from each issued loan is distributed among the owners of $DLP (contract address). APY's annualized return is currently ~40%. If you don't know what this means yet, we encourage you to read our post on the topic — What is the difference between APY and APR? Recently, the team announced an incentive program for holders of the $LLAMA project token — regular repurchase of coins from the market directly through #DEX, which is very important, and sending these tokens to their holders. ↗️ As the project grows, the ransom amounts will increase, but the dates will be kept secret to avoid manipulation of the coin rate. So in the long run it sounds very tasty for #LLAMA. And now the most interesting... ❤️ Each user who follows our referral link will receive a 100% discount, as well as 10% more $TON for the first loan or purchase on credit on the DaoLama marketplace. #DaoLama#staking#TON

💛 Storm joins the 🦙 DAOLama contest! We previously shared details about the DAOLama Team x TON Society event, which unlocked unique opportunities for holders of Telegram Anonymous Numbers 🐸Now, Storm Trade is joining the initiative — meaning you can now earn additional leaderboard points by using your TON-backed loans directly on the #Storm platform! Here’s how it works: ⚫️ Use your Telegram Number NFTs as collateral to borrow TON ⚫️ Earn 1 point on the leaderboard for every 1 TON borrowed ⚫️ Trade on Storm Trade with margin in TON to gain +0.25 points for each TON used ⚫️ Climb the leaderboard and earn rewards and utilities from DAOLama 🤝Storm and DAOLama are teaming up to bring even more opportunities to participants — don’t miss your chance to get involved! #DAOLama#SBT#DeFi#TONSociety#StormTrade