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

Резултати

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

Пребарај: #gateio

当前筛选 #gateio清除筛选

ℹ️Join GODL Pre-Deposit to Split $30,000 💰 During the event, complete GODL pre-deposit on #Gateio CEX, users can share in a 🏆 $30,000 prize pool based on their ranking by pre-deposit volume. 🏆 Everyone is eligible to win a share, ensuring a 100% reward. More GODL — more rewards! 7 November, 2024 $GODL Listing Date! 🔥 3️⃣Days to go until HODL GODL

Hashtags

SpotOnChain | Announcement

@spotonchain · Post #814 · 09.05.2024 г., 03:44

The Render Network appears to keep depositing $RNDR to CEX after the price surged ~40% (7D). In the past hour, wallet 0x537 (linked to Render Network) moved 323K $RNDR ($3.36M) to #Gateio and GSR Markets for future CEX deposits. Since last Jan, the wallet has received 8.1M $RNDR ($67.9M) in total from Render Network and deposited 6.52M $RNDR ($56M) to CEX, often before the price dropped (pic👇). Follow @spotonchain and set alerts for the wallet and $RDNR for the next important whale activities now: 1. Wallet 0x537: https://platform.spotonchain.ai/en/profile?address=0x53743ac55e434f8aa5097f038b13193497d54d42 2. $RNDR: https://platform.spotonchain.ai/en/token?name=RNDR

Hashtags

SpotOnChain | Announcement

@spotonchain · Post #916 · 20.07.2024 г., 01:55

Early whale “arthurgayes.eth” moved the first 2T $MOG ($4.41M) to #Bybit & #Gateio 9hrs ago as the price soared! This whale bought 8.26T $MOG with just 251K $USDC in Sep-Oct 2023; And still holds 6.26T $MOG (~$14M) in 3 wallets, making an est. total profit of $18.1M (x72)! Follow @spotonchain and check out the whale’s wallet addresses via this signal: https://platform.spotonchain.ai/en/signal-details/whale-deposited-the-first-2t-mog-441m-to-cexs-for-profit-147215

SpotOnChain | Announcement

@spotonchain · Post #834 · 24.05.2024 г., 02:16

Three fresh multisigns have withdrawn 43.19M $ENA ($35.68M) from #Gateio and #Bybit in the past week! With the price surging 28% (7D), these wallets are making $2.05M in unrealized profits. Are whales bullish on $ENA, a $ETH beta token, thanks to recent Ethereum ETF approval from the SEC? Follow @spotonchain for set alerts for the multisigns via this token flow: https://platform.spotonchain.ai/en/visualizer?timeRange=4&id=131559&thresholdOption=3

SpotOnChain | Announcement

@spotonchain · Post #1291 · 22.09.2025 г., 10:33

Whale locks in profits after a +185% gain on $ASTER — in just 4 days! On Sep 18, wallet "0xeE7" spent 1.21M $USDT to buy 2.086M $ASTER at $0.58 via #Aster. 21 hours ago, they deposited 1.043M $ASTER ($1.74M) to #Gateio at $1.67 — likely reclaiming the principal + ~$500K in profit before the market dropped. Now holding the remaining 1.043M $ASTER ($1.7M) as pure profit. Follow @spotonchain for more smart money insights. https://x.com/spotonchain/status/1970073217089102150

Walken.io - Announcement

@walken_channel · Post #244 · 23.07.2022 г., 14:09

🤑Gate.io Startup Answer & Earn @walken_io💵 📝Take the quiz about Walken(WLKN) & Split a $3,000 mega prize!🏆 ⏰Ends at 9:00AM, Jul 25th (UTC) *How to participate: ✅ Join GateioOfficialNews and Walken community ✅Follow @Gateio_Startup & RT the 👉POST 🔛 Click 👉HERE to Participate now Learn More:https://www.gate.io/startup #Gateio#gateiostartup

SpotOnChain | Announcement

@spotonchain · Post #793 · 24.04.2024 г., 01:54

Whale 0x803 (linked to “rektdolphin.eth”) has been steadily accumulating 211.6B $PEPE (now $1.72M) in the past 24 hours, as the price surged back by 17%! Notably, the whale: • accumulated PEPE from #Binance, #Gateio, and #Uniswap at ~$0.000007291 (est. cost: $1.54M), now making $173K (+11%) in unrealized profit; • last withdrew $PEPE only an hour ago and may continue accumulating more tokens. Follow @spotonchain and set alerts for the whale at https://platform.spotonchain.ai/en/profile?address=0x803c21672a2d3c512bda8c0337dff9a850dd669d

SpotOnChain | Announcement

@spotonchain · Post #1292 · 24.09.2025 г., 09:46

🔥$ASTER up 38% today — who’s fueling the pump? 1️⃣ Whale “0xFB3” deposited 73.95M $USDT into #Gateio and withdrew back 24M $ASTER ($46.6M) ~16hrs ago. 2️⃣ Fresh whale “0x5bd” withdrew 6.72M $ASTER ($13.3M) from #Bybit over the past 16 hours. 3️⃣ Fresh whale “0x8bc” swapped 1.19M $USDT for 595,580 $ASTER in one transaction at $2 per token ~20hrs ago. 4️⃣ Whale “0x5e3” swapped 1,090 $BNB ($1.11M) for 549,194 $ASTER in one transaction at $2 per token ~11hrs ago. 📈🚀 The 24h perp volume on #Aster (@Aster_DEX) just hit $24B+ — over 2x that of #Hyperliquid! Follow @spotonchain for more updates now! https://x.com/spotonchain/status/1970785540057530740

SpotOnChain | Announcement

@spotonchain · Post #850 · 07.06.2024 г., 03:07

As the #memecoin $BRETT price up by 30% (2D), early buyers/insiders are selling for profits! In the last 32 hours, 5 wallets have deposited 71.76M $BRETT ($9.94M) to #Gateio, #KuCoin, and #Bybit, causing the price to dip after each transfer. Notably, these wallets: • belong to a group of 15 wallets that swapped 4.9 $ETH ($14.4K) for 1.86B $BRETT, or 18.6% of the total supply, within 45 minutes of the token creation on Feb 25. • still have 941.4M $BRETT ($132M) left! Follow @spotonchain for more updates on #memecoin activities and set alerts for the entity of $BRETT early buyers/insiders via https://platform.spotonchain.ai/en/entity/2061

🍅Pre-deposit 🪙$TOMA on CEX and $200,000 bonus #Tomarket is preparing to enter two leading exchanges — #Gateio and #Bitget! 💰$TOMA Listing Confirmed on Gate.io: Starting from December 20, 2024 at 12:00 PM (UTC), $TOMA trading will start on the Gate.io exchange. 💱$TOMA output is open on Bitget: Pre-deposit for $TOMA opens on Bitget exchange on December 13th at 8:00 UTC. Token holders can deposit their assets without gas fees and get a chance to earn up to $100 in $TOMA tokens from a total prize pool of $200,000 ! The promotion periodis from December 13 to 18 — act quickly!✈️ Participation in the promotion is carried out on a first come, first served (FCFS) basis, so make sure to contribute your $TOMA and become one of the lucky ones who receive additional rewards! 🪙Go to the app, open the Airdrop tab and choose the method of sending tokens. ℹ️ To withdraw you will need your TOMA address on the Bitget exchange: Bitget\TOMA\Deposit (Aptos network) + your UID #Tomarket#TOMA#Gateio#Bitget#CryptoNews#Airdrop

Your Own Ads

@yourownads · Post #190 · 12.02.2025 г., 12:09

📈#Gateiopartner carnival: the main prize of $12,000 is being played out 🔥 The promotion is active until 11:00 Moscow time on February 24 ℹ️How to earn: 1) Registration on Gate + KYC2 2) Go here and click "Join now" 3) We complete the tasks: 🎁BONUS 1 : Registration + KYC, PrizeStartup voucher for 20 shares 🎁BONUS 2 : Make a deposit of $50, prize from $5 to $10 🎁BONUS 3 : Make a trading volume of $200, split the prize pool of $10,000 depending on the share in the total trading volume 🎁BONUS 4 : Invite users and share the prize pool of $2000 🔗Join now and earn: https://gate.io/fr/campaigns/396?ref=VLJMULHBVA #Gateio#GateioStartup#Crypto

ПретходнаСтраница 1 од 3Следна