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

Резултати

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

Пребарај: #presale

当前筛选 #presale清除筛选

​​🎙 INVEST REPORT Injex Finance - The 1inch of Injective 🔥🥷 ⚖️ INVEST REPORT project rating 9/10 ⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️ It is the final day of Round 1 in $INJX Presale, and this is your moment to act before the price jumps. Join Presale: https://sale.injex.fi/ Don’t let this chance slip through your fingers! Secure your $INJX tokens now at the most favorable price. Join the future of decentralized finance on the Injective chain. Act now, join the presale. https://sale.injex.fi/ #INJ#Presale

Hashtags

Airdrop Strikers™

@airdropstrikers · Post #660 · 28.09.2022 г., 12:10

#PoshCoin#Presale Public Presale Started NOW! ℹ️ Info About PoshCoin: PoshCoin is a new crypto token that will revolutionize the digital economy – mainly selling and purchasing goods in the cannabis sector. PreSale Link:https://www.pinksale.finance/launchpad/0xD90267576273A0d640850De1beFdF366744C13DB?chain=BSC ⚜️ Token Information 🔶Token Name: Poshcoin 🔶 Symbol: PSCN 🔶Type: BEP-20 🔶 Minimum Buy: 0.0035BNB 🔶 Maximum Buy: 35BNB 🌐 Useful links : Telegram Channel Platform: https://t.me/PoshCoinPSCN Telegram platform group: https://t.me/poshcoin_pscn JOIN PRESALE NOW! Disclaimer: Please do your own research before joining to any project.

Airdrop Strikers™

@airdropstrikers · Post #583 · 01.09.2022 г., 13:53

#MetaCubez#Presale A Metaverse Full of Possibilities ✔️ Licenced From Singapore and UAE ✔️ Audited Smart Contract ✔️ KYC Team ✔️ 30% Burnt ✔️ 60% Locked ✔️ Professional team from all around the world MetaCubez Pre-Sale is Live Now!🔥🔥 https://linktr.ee/MetaCubez Check out there Social Links Channel | Community | Website | Instagram | Discord | Twitter

Airdrop Market Pro

@airdrop_market_pro · Post #361 · 29.03.2023 г., 00:06

🚨🚀 Exciting news for all crypto enthusiasts! 🌟🤑 🚨🚀 25% of DLX tokens will be available for pre-sale on Pinksale Finance from April 25-30, 2023. This is a rare opportunity to invest in one of the hottest tokens on the market! #PinksaleFinance#presale💰💸💎 Hey all you crypto enthusiasts! We've got some awesome news to share - the pre-sale for DLX tokens on Pinksale Finance is starting soon! From April 25-30, 2023, 25% of the total DLX token supply will be available for purchase. Don't miss out on this chance to invest in one of the hottest tokens on the market! #PinksaleFinance#presale💰💸💎 🔥👇 Web site Dollex Network https://dollox.network/ ‼️Note: We are airdrop hunters and only participate in free airdrops, please do not send any fee for receiving airdrop tokens.

NFT & Airdrop News

@airdrop_nft1 · Post #360 · 29.03.2023 г., 00:06

🚨🚀 Exciting news for all crypto enthusiasts! 🌟🤑 🚨🚀 25% of DLX tokens will be available for pre-sale on Pinksale Finance from April 25-30, 2023. This is a rare opportunity to invest in one of the hottest tokens on the market! #PinksaleFinance#presale💰💸💎 Hey all you crypto enthusiasts! We've got some awesome news to share - the pre-sale for DLX tokens on Pinksale Finance is starting soon! From April 25-30, 2023, 25% of the total DLX token supply will be available for purchase. Don't miss out on this chance to invest in one of the hottest tokens on the market! #PinksaleFinance#presale💰💸💎 🔥👇 Web site Dollex Network https://dollox.network/ ‼️Note: We are airdrop hunters and only participate in free airdrops, please do not send any fee for receiving airdrop tokens.

Airdrop Strikers™

@airdropstrikers · Post #504 · 22.07.2022 г., 14:37

#SVC#presale#Sponsored 💎Smart Vision Coin Public Presale is now LIVE 💎Presale Link : https://www.pinksale.finance/launchpad/0x662Da19fDeF9B8B23636dDBfcDDd63013eE00911?chain=BSC ✅Token Name: Smart Vision Coin (SVC) ✅Token Address:0xAAc82B1d9fFE7c50fd2d5C8b0d3a0d8E3a374b03 ⏲Presale Time: 07/21 06:00AM ⏲Ends Time: 08/20 23:59PM 💰Soft/Hard Cap: 1,500 BNB / 3,000 BNB 💰Min/Max: 0.01 BNB / 10 BNB 💰Presale Rate: 1 BNB = 3,800,000 SVC 💰Listing Rate: 1 BNB = 2,300,000 SVC 🔓Liquidity: 51% 🔓Liquidity Lockup Time: 365 days 👉Telegram: https://t.me/svc_coin 👉Telegram Channel: https://t.me/svc_coin_channel 👉Twitter: https://twitter.com/svc_coin 👉Website: https://www.smartvisioncoin.net/

Airdrop Market Pro

@airdrop_market_pro · Post #1386 · 02.10.2025 г., 15:08

💎 MetaGram Presale — Early Investors’ Edge! Be among the first to secure $MGR before listing at $0.0519. ⚡️ Buy & Earn instantly with our new swap-style UI: 0.001 BNB → 50 $MGR (free airdrop) 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB back 🔥 Early entry = maximum upside. Don’t wait until the price goes public. 👉metagram.digital #MetaGram#Presale#BNB#Crypto

Airdrop Market Pro

@airdrop_market_pro · Post #1385 · 01.10.2025 г., 20:18

We’ve refreshed the MetaGram presale page! New swap-style UI = faster, clearer, mobile-friendly buying. 🚀 Don’t miss the Presale & Airdrop 💎 0.001 BNB → 50 $MGR (airdrop) ⚡️ 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB 🔥 Listing price: $0.0519 / MGR 👉https://metagram.digital/airdrop #MetaGram#BNB#Presale#Crypto

Airdrop Market Pro

@airdrop_market_pro · Post #1383 · 29.09.2025 г., 16:38

We’ve refreshed the MetaGram presale page! New swap-style UI = faster, clearer, mobile-friendly buying. 🚀 Don’t miss the Presale & Airdrop 💎 0.001 BNB → 50 $MGR (airdrop) ⚡️ 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB 🔥 Listing price: $0.0519 / MGR 👉https://metagram.digital/airdrop #MetaGram#BNB#Presale#Crypto

NFT & Airdrop News

@airdrop_nft1 · Post #1382 · 02.10.2025 г., 15:08

💎 MetaGram Presale — Early Investors’ Edge! Be among the first to secure $MGR before listing at $0.0519. ⚡️ Buy & Earn instantly with our new swap-style UI: 0.001 BNB → 50 $MGR (free airdrop) 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB back 🔥 Early entry = maximum upside. Don’t wait until the price goes public. 👉metagram.digital #MetaGram#Presale#BNB#Crypto

NFT & Airdrop News

@airdrop_nft1 · Post #1381 · 01.10.2025 г., 20:18

We’ve refreshed the MetaGram presale page! New swap-style UI = faster, clearer, mobile-friendly buying. 🚀 Don’t miss the Presale & Airdrop 💎 0.001 BNB → 50 $MGR (airdrop) ⚡️ 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB 🔥 Listing price: $0.0519 / MGR 👉https://metagram.digital/airdrop #MetaGram#BNB#Presale#Crypto

NFT & Airdrop News

@airdrop_nft1 · Post #1379 · 29.09.2025 г., 16:38

We’ve refreshed the MetaGram presale page! New swap-style UI = faster, clearer, mobile-friendly buying. 🚀 Don’t miss the Presale & Airdrop 💎 0.001 BNB → 50 $MGR (airdrop) ⚡️ 0.01 BNB → 500 $MGR 🤝 Referrals: +50% $MGR & +50% BNB 🔥 Listing price: $0.0519 / MGR 👉https://metagram.digital/airdrop #MetaGram#BNB#Presale#Crypto

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