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

Резултати

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

Пребарај: #june2023

当前筛选 #june2023清除筛选
The Open Platform

@topco · Post #67 · 04.07.2023 г., 08:59

DeFi: June headlines - Real-world asset protocols outperform DeFi blue chips due to tokenization wave. The top uncollateralized lending protocols for institutions, TrueFi and Maple, have increased by 26.6% and 117.8%, respectively, in 2023. Centrifuge, a real-world asset tokenization platform, has surged by 32% year to date (source). - DeFi Platform EigenLayer Rolls Out Restaking Protocol on Ethereum Mainnet, EigenLayer's developers raised $64.5 million in a series of investment rounds (source). - Arbitrum-Based DeFi Project Chibi Finance Rug Pulled: Over $1 Million Drained: On-chain analysis conducted by blockchain security platform CertiK revealed that Chibi devs deployed a malicious contract that enabled them to steal user funds from the protocol’s smart contracts (source). - DeFi Protocol Maverick Raises $9M Led by Peter Thiel's Founders Fund, the round also included contributions from Pantera Capital, Binance Labs, Coinbase Ventures and Apollo Crypto (source). - BlackRock Executive: Knowing Who Counterparties Are Is Key to Engaging Institutions in DeFi. Issues such as the automated market making in DeFi instead of central order limits books are just fig leaves, said Chalom. "We need clear understanding of who is in a pool" (source). #DeFi#trends#June2023

The Open Platform

@topco · Post #70 · 07.07.2023 г., 09:02

Metaverse: June headlines - Consumers appear less interested in more futuristic offerings, want real-world applicability, are least interested in fashion and beauty, loosing interest in metaverse socializing - McKinsey & Company (source) - Apple bets on the metaverse: Apple unveiled its long-awaited entry into virtual reality, or what the tech giant calls “spatial computing,” in the form of the Apple Vision Pro, a $3,500 device that looks like exquisitely designed futuristic ski goggles (source). - Banks Have Come to the Metaverse. JPMorgan arrived in Decentraland under the brand Onyx, which, according to the company, is “a blockchain-based platform for wholesale payment transactions.” DBS, Singapore’s biggest bank, purchased a large plot of land on The Sandbox to develop interactive experiences aimed at promoting a more sustainable world. South Korea’s Kookmin Bank has its own native metaverse-based financial services as well as one-on-one customer service (source). #metaverse#trends#June2023

The Open Platform

@topco · Post #69 · 06.07.2023 г., 09:02

Web3 Creator Economy: June headlines - Mythical Games Secures First Close of $37 Million Towards Latest Round of Funding. The round was led by digital asset manager Scytale Digital, with participation from ARK Invest, Animoca Brands, PROOF, Stanford Athletics, MoonPay. Existing investors, including Andreessen Horowitz, Gaingels, Signum Growth, Struck Capital, and WestCap also participated in the round. Mythical is a next-generation games technology company creating a web3 gaming ecosystem by leveraging blockchain technology and playable NFTs for tools that enable players, creators, artists, brands and game developers to become stakeholders and owners in new “play and own” game economies (source). - NFT Creation Platform Zora Launches Creator-Focused Layer 2. In a statement to CoinDesk, a spokesperson for Zora said that the platform has been building a "culture of creativity and community" since its inception, putting artists and creators at the forefront of its products (source). #creatoreconomy#trends#June2023

The Open Platform

@topco · Post #68 · 05.07.2023 г., 09:01

Wallets / Payment Solutions: June headlines - PayPal invests in new crypto wallet service. PayPal has announced a substantial investment in Magic, the strategic funding round, led by PayPal Ventures, raised $52 million for Magic, with additional investments from Cherubic, Synchrony, KX, Northzone and Volt Capital (source). - Atomic Wallet Hackers Use THORChain to Conceal Stolen $35M Funds: the hackers, believed to be North Korean hacking group Lazarus, have been using cross-chain bridges and liquidity protocols to mix stolen funds (source). - Crypto​.com joins ranks of licensed payment institutions in Singapore: with the MPI license, Crypto.com is now authorized to offer its DPT services to customers in Singapore (source). - Crypto Payments Firm Wyre Winding Down Due to ‘Market Conditions’. Wyre is ceasing operations less than a year after it was valued at $1.5 billion in an abortive acquisition by Bolt (source). - Binance struggles in Europe continue as it has lost its EURO payment partner - Paysafe,its Euro payment partner, will stop its bank transfers services from September 25 (source). - Mastercard plans beta for a blockchain ‘app store’ for ‘regulated’ financial apps. Mastercard said it was planning to launch a beta in the U.K. over the summer to test what it calls the Multi Token Network, or an “app store powered by blockchain technologies for building regulated financial applications” (source) #wallet#paymentsolutions#trends#June2023