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

Резултати

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

Пребарај: #mytonwallet

当前筛选 #mytonwallet清除筛选

MyTonWallet v3.5 – let's take a look! 💎What has changed: 🫥The transaction feed has become more convenient and informative. "Change" and technical transactions are now grouped and do not interfere with viewing the history, and token icons are displayed during exchange. You can even see the average purchase price of a coin – very convenient 🩷 🫥Hiding the balance – the button is located at the top of the card on the main screen. 🫥 Now creating a deposit link, you can select any TON-token in which you want to receive funds to your wallet. 🫥MyTonWallet NFT cards provide access to advanced interface personalization. All palettes can be seen in the settings. 🔄 Since March 27, the service fee for $MY token exchanges in pairs with TON and USDT has been removed. The #MyTonWallet team hinted that they are working on further updates and exploring new blockchains. 👀 Channel | Chat | Mini-app

Hashtags

TONlines – News

@tonlines · Post #7464 · 31.05.2025 г., 12:59

Updates from TON — LIVE: New Features in MyTonWallet #TON#MyTonWallet TON — LIVE reports that MyTonWallet has introduced an update allowing for mass transfers of TON and tokens in a single transaction, along with new options for renewing multiple TON DNS domains simultaneously. Source: link @tonlines

TONlines – News

@tonlines · Post #6990 · 30.04.2025 г., 16:12

TON — LIVE: MyTonWallet v3.6 Update Released #MyTonWallet#TON TON — LIVE reports that MyTonWallet has released update v3.6, introducing the ability to view any TON and TRON addresses and share links to transfers immediately after sending. The update also includes action previews in dApp and auto-unlock via PIN. Source: link @tonlines

TONlines – News

@tonlines · Post #6922 · 23.04.2025 г., 19:01

TON — LIVE: MyTonWallet to Launch Bank Cards #MyTonWallet#TON The TON — LIVE channel reports that MyTonWallet is planning to introduce bank cards. This development could enhance MyTonWallet's service offerings. Source: link @tonlines

TONlines – News

@tonlines · Post #6820 · 17.04.2025 г., 15:45

TON — LIVE: MyTonWallet Unveils NFT Card Minting #MyTonWallet#NFT MyTonWallet has introduced NFT card minting, available for only 50 active users. These cards offer unique wallet design customization, with more features to be announced soon. Source: link @tonlines

🌿🌸 Spring is Here! Fresh Features from MyTonWallet v3.4 😎The most important news In version v3.4, a mini-app #MyTonWalletappeared inside Telegram. Now you can use your favorite wallet in TMA format 🩷 — @myapp. Just import the Seed phrase from your current TON wallet and you can use it 🤑 Changes and new features: 🔵Knowledge base – a new section in the wallet settings (there is also a direct link to the guides ). For beginners, this is a very useful feature, as there is a lot of information about working with #web3 environment. 🔵 Several new features have been added for working with addresses and transactions. 🔵Transparent fees in TON Connect are a very convenient addition that allows you to see the size of $TON fees 💎Channel | Chat | Mini-app

TONlines – News

@tonlines · Post #7453 · 30.05.2025 г., 12:17

TON — LIVE: Integration of USDe Stablecoin in MyTonWallet #Ethena#MyTonWallet TON — LIVE shares that the USDe stablecoin from Ethena is now integrated into MyTonWallet. Users can also participate in staking with returns up to 18% annually. Source: link @tonlines

TONlines – News

@tonlines · Post #7033 · 03.05.2025 г., 08:20

⚡️Storm Trade: STORM Token Rewards Distributed #STORM#MyTonWallet Storm Trade has announced that rewards in STORM token from the MyTonWallet contest have been successfully distributed. Wallet holders are advised to check their balances. Source: link @tonlines

TONlines – News

@tonlines · Post #6761 · 14.04.2025 г., 17:06

⚡️Storm Trade News: Join the $STORM Trading Tournament! #STORM#MyTonWallet Storm Trade | News has partnered with MyTonWallet for a trading tournament, offering $2,500 in prizes for top $STORM traders. Participants can earn cashback and stake $MY to reduce fees. The tournament runs from April 14–29. Source: link @tonlines

🎙New Interview with the Creator of MyTonWallet TON App Journal recently published a written interview with Alexander Zinchuk, the founder of 💎MyTonWallet. If you're curious about the project’s philosophy and the team’s vision, it’s definitely worth a read Highlights from the conversation: 🔵#MyTonWallet is built on the principles of freedom, user respect, and decentralization. 🔵Security, transparency, and ease of use are top priorities. Features like TON Proxy and multichain standards help make the TON ecosystem more accessible. 🔵 The team is made up of experienced developers focused on minimalist design and intuitive UX. 🔵#MTW was the first wallet on TON to undergo a CertiK audit. 🗣We’re currently working closely with TON Core, DeDust, and Tonscan to improve the speed of transfers and swaps within the network — and that’s just the beginning🗣 , says Alexander. 📖The MyTonWallet blog has been live for nearly six months, sharing major updates and release news (also mirrored in their Telegram channels). 💡 The team also published an important breakdown of a seed phrase theft scheme — a must-read for newcomers.

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