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

Резултати

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

Пребарај: #username

当前筛选 #username清除筛选
BotsGram®

@botsgram_cu · Post #4399 · 03.10.2021 г., 03:22

¿Que puede hacer este bot? @idtousername_bot Este bot puede convertir cualquier ID numérico (ejemplo: 123456789) en un enlace de perfil. También puede ver su ID numérico en este bot. Idiomas: inglés (Visto en @botsgram_cu) #id#username

Hashtags

New Feature Alert: Username Auction on Split.tg! 🚫 With KYC now mandatory on fragment.com, users without KYC were unable to list their usernames for auction. But not anymore! 👍 Now you can start username auctions directly on split.tg — no KYC required. Just a 1% fee. 👍 👍Ready to get started? Visit split.tg/auction and take full control of your Telegram usernames today! #username#NFT#TON#NoKYC

The $17K Mistake: How a Simple Username Sale Became a Nightmare Probably everyone has already heard about fraudulent schemes with anonymous numbers and usernames through the fake website fragment.com✅ but it seems worth reminding again using the example of a situation in which one of our community lost 15k $USDT and 365 $TON Original Yesterday afternoon a guy with the nickname ⚠️@Yennypp⚠️wroteme , with a question about whether I was selling my username@matildasion. I blurted out a price of 200 TON, he agreed and suggested doing everything right away through - Fragment. I wrote to him that I don't have verification on the fragment, to which he replied that if you are making an offer, you don't need it. In general, nothing suspicious, I sent a link to the offer itself, interestingly, it opened only with the included VPN in the form of a Mini App. Then I unlinked my user and followed the link, the Fragment website opened and the price was 212 TON for my user, a timer was also set for 23:59:NN (after this time the offer expires). I started the sales process (as I thought). It suggested linking a wallet (I chose the main Tonkeeper), then it was necessary to confirm the transaction in the keeper, it was displayed as “failed”, I went in again on the same one, I figured in my head that: - “this is the keeper, it’s probably slow” I signed. The result is on the screen. Then this guy asked to confirm the transaction again and offered to add a ton for the commission... Victim's TON-wallet: matildasion.ton This situation once again shows that you need to be more careful when signing a transaction and remember the main signs of a scam: 1. You are offered conditions that are much higher than the market 2. You are being rushed due to some "circumstances" 3. You are offered to make a transaction in a non-standard way under the pretext of a high commission or "for your own convenience" If you want to support the person who suffered in this story, you can donate any amount that is comfortable for you in any tokens to the wallet: UQCevAC0E72kTNqn5QkpCx8fxVvpdCpfzGo753o3Zf80yP2y P.S. we have known each other in absentia for over two years, he has a confirmed merchant on @wallet #scam#fragment#username