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

Резултати

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

Пребарај: #fton

当前筛选 #fton清除筛选

The long-awaited listing of the token from Fanton Fantasy 🟨 We would like to remind you that #FTON is a utility token of the Fanton Fantasy project, necessary for playing in their tournaments. Token holders will be able to participate in betting and ⛏ farming, receive in-game bonuses, and also have the exclusive right to purchase NFT cards of the project. ↗️ The listing of $FTON will take place on October 1 at 13:00 UTC (16:00 Moscow time) on three CEX exchanges at once: Kucoin, Gate.io , MEXC. In our 🪙#TON network, the pool will appear at 13:15 UTC and unfortunately only on 1 DEX exchange – Ston.FI. At the same time, the team itself states that they are working with other sites on the token listing, so we are waiting for announcements. ➖After listing, life is just beginning, and we will begin to systematically increase the utility for $FTON, both for Fanton Fantasy players and ordinary cryptans! The team also reminded us that Notcoin and Tonstarter are among their key partners: ➖Over the past 1.5 years, we in the Fanton team have held many calls with the creators of the best platform for social campaigns — Community, as well as Notcoin, which blew up TON and Telegram in early 2024. ➖Since then, we have been calling the guys weekly, maintaining a connection on the topic of launchpads and launching ⚽️ $FTON, received expertise and connections, and are finally close to launching our utility token. Fanton | News | Chat | ChainGPT

Hashtags

TONlines – News

@tonlines · Post #6842 · 18.04.2025 г., 16:26

Fanton EN: New Legendary NFTs and Staking 2.0 #NFT#FTON Fanton EN presents the new Staking 2.0, featuring a convenient chart and distinguished Legendary NFTs, including players like Batrakov and Osipenko. The first round of NFT distributions for FTON stakeholders will start tomorrow. Participants can exchange injured NFTs through support. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6849 · 18.04.2025 г., 23:12

⚡️Fanton EN: Launch of Staking 2.0 #Fanton#FTON#NFT Fanton EN channel has announced the launch of Staking 2.0 in the game, offering lucrative opportunities for players. By staking $FTON tokens, participants can earn rewards surpassing the token’s value and receive additional NFTs. Important deadline: Stake before April 19 to secure your NFT before the 25th RPL round. Source: link @tonlines

TONlines – News

@tonlines · Post #6841 · 18.04.2025 г., 16:01

⚡️Fanton EN: Launch of Staking 2.0 with NFTs and Tournaments #FANTON#NFT#FTON Fanton EN introduces Staking 2.0, featuring NFTs, tournaments, and appealing bonuses. Participants can stake FTON in four different pools, each offering unique rewards like NFT cards, tournament entry, and up to 10% APY. The update includes guaranteed RPL NFTs and the opportunity to join exclusive pools with limited slots. Source: link @tonlines

TONlines – News

@tonlines · Post #7022 · 02.05.2025 г., 08:51

⚡️Fanton EN: May Leaderboard Kicks Off with New Rewards #FTON#NFT#RPL Fanton EN has announced the results for April with $FTON and NFT card distributions to players. The May Leaderboard requires participants to earn at least 50 trophies to share a 1 million $FTON prize pool. Top players will also receive Rare RPL cards, selected based on rank. Source: link @tonlines

🏷 Start of presale from Fanton 🟡Placement will take place on August 7th at 11:00 UTC on the Magic Square platform 🟡Presale price – $0.023 (5% discount to the IDO price) 🟡Total raised amount – $150,000 🏆 We want to remind you that $FTON is a utility token for the Fanton Fantasy game, necessary for playing in project's tournaments. Token owners will be able to participate in staking and ⛏ farming, receive in-game bonuses, and also have exclusive right to purchase NFT cards of the project. The first part of FCFS/Whitelist Round: 🟨Create an account on Magic Square and go through KYC 🟨Use wallet which completed the Zealy campaign 🟨Click "Join Whitelist" Second part of the ProRata Round will begin on August 8th at 11:00 UTC. 📊 Allocation will depend on thr amount you contributed in relation to other participants. Trading with other users (until TGE) will appear on Magic Square OTC marketplace. More information in detailed guide - link here. #fanton#magicsquare#fton