Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
STON.fi (Telegram)
🗿Impermanent Loss Protection: 2322 STON Sent to Liquidity Providers
Stonfiers! We've distributed STON 2322 STON offset to liquidity providers in the STON/USDT pool for December 1-31. Check your wallets!
💎 Here's what you need to know:
• You can offset up to 5.72% of your impermanent loss.
• Monthly protection budget: $10,000.
• Max offset per user: $100 in STON tokens.
• Auto-crediting — no need to claim!
🚨Important: Users who provided liquidity in theSTON/USDTpool before January 1 will be protected from impermanent loss until January 31!
🔗Add Liquidity Now🔗
#protection#liquidity
DEX | Telegram DEX | Onboarding | Guide | Blog | All Links
🐣X🤖Discord🌐Reddit🌐LinkedIn📹YouTube🪨Join the Club
STON.fi: Impermanent Loss Protection for Liquidity Providers
#protection#liquidity
STON.fi has distributed 6546 STON tokens to liquidity providers in the STON/USDT pool for November, with up to 5.72% impermanent loss offset offered. Users who provided liquidity before December 1 will have protection until December 31, with a monthly budget of $10,000.
Source: link
@tonlines
STON.fi: New Round of Impermanent Loss Protection Starts Soon
#protection#liquidity
STON.fi reminds liquidity providers that the new cycle of impermanent loss protection for the STON/USDT V2 pool begins on May 1st. Only those joining the pool by then will be eligible for protection.
Source: link
@tonlines
STON.fi Update: IL Protection Sent to Liquidity Providers
#protection#liquidity
STON.fi has distributed 894 STON to liquidity providers in the STON/USDT v2 pool for March 1-31, offering up to 5.72% impermanent loss offset. With a monthly protection budget of $10,000 and a max offset of $100 per user, auto-crediting ensures no claiming is needed.
Source: link
@tonlines
¿Que puede hacer este bot?
@NewUsersMediaLimiterBot
Este nuevo bot que limitará el envío de medios a los usuarios que acaban de unirse al grupo durante los primeros 30 minutos, a menos que sean desmantelados manualmente por uno de los administradores, el bot no enviará ningún mensaje cuando el usuario ingrese.
Idiomas: italiano inglés
(Visto en @botsgram_cu)
#grupos#administración#protection
🌍 Earth's magnetic field acts like a protective shield, deflecting harmful solar wind and cosmic rays. This invisible force helps preserve our atmosphere and supports life on the planet. ✨
#magnetism⚡#protection⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Souveraineté Alimentaire : Les dirigeants de l’AES doivent mettre un terme à l'accord de libre-échange et de coopération, par le biais duquel les États de la région ouest-africaine s'engagent à libéraliser progressivement leurs marchés au profit des importations en provenance d'Europe.
Il est essentiel de prioriser le renforcement des moyens et du soutien en faveur de nos agriculteurs locaux, plutôt que de continuer à inonder notre continent avec des denrées alimentaires européennes de qualité souvent médiocre, entraînant ainsi l'apparition de nouvelles maladies tropicales. #souverainetéalimentaire#Afrique#Protection
@egountchibehanzinTV
🇺🇿Oliy maktabda magistrlik dissertatsiyalari himoyasi bo‘lib o‘tdi
🔈 Joriy yilning 10\11-iyun kunlari Biznes va tadbirkorlik oliy maktabida 70411302 – Biznesni boshqarish (MBA) hamda 70411301 – Kichik biznes va xususiy tadbirkorlik (Biznes innovatsiyalar va tadbirkorlik) magistratura mutaxassisliklari tinglovchilari uchun Yakuniy davlat attestatsiyasi doirasida magistrlik dissertatsiyalari himoyasi bo‘lib o‘tdi.
🔼 Jami 23 nafar tinglovchi, jumladan Biznesni boshqarish (MBA) mutaxassisligi bo‘yicha 10 nafar, Kichik biznes va xususiy tadbirkorlik mutaxassisligi bo‘yicha 13 nafar tinglovchilar magistrlik dissertatsiyalarini muvaffaqiyatli himoya qilishdi.
👨🎓
📔 Magistrlik dissertatsiyalari O‘zbekiston Respublikasi Prezidenti huzuridagi Davlat boshqaruv akademiyasi kafedra mudiri, professor, Yakuniy davlat attestatsiyasi komissiyasi raisi D.Raximova hamda komissiya a’zolari tomonidan baholandi. Dissertatsiyalarni himoya qilish jarayoni ilmiy mubohasa yo‘sinida va yuqori talabchanlik bilan o‘tkazildi.
🌀Batafsil
#GraduateSchool#Protection#Dissertation#Work
🌐Web-site |
✅Telegram |
✅Facebook |
🌐Instagram
🔥 Сегодня
🔥 Вебинар PETYA, МАЙНИНГ, UEBA
📅 20 марта / 11:00 — 12:30 (время МСК) / онлайн
💵 Бесплатно
📝 Регистрация тут: https://goo.gl/1HJ68T
Как не повторить ошибок 2017-го и войти в 2018 год во всеоружии, заранее знать основные угрозы и как с ними бороться, на практических примерах расскажет руководитель экспертного отдела «Гарда Технологии» Роман Жуков.
🔗 Программа: https://goo.gl/1HJ68T
#security#cybersecurity#protection#онлайн
#go#attacks_prevention#detection#linux#protection#security
CrowdSec is an open-source security solution that helps protect servers from malicious IP addresses. It uses a community-driven approach, where users share information about threats they've faced, creating a shared blocklist to prevent attacks. CrowdSec's Security Engine can detect bad behaviors by analyzing logs and HTTP requests, and it supports multiple platforms. This system is fast, easy to use, and designed for modern infrastructures, making it a powerful tool for securing your systems against various threats. By using CrowdSec, you benefit from collective protection and can focus on real security issues.
https://github.com/crowdsecurity/crowdsec
@littleGuardianBot
Qué puede hacer este bot?
LittleGuardian fue creado como un bot para apoyar los esfuerzos de los administradores del grupo Telegram mientras luchaba con comportamientos antisociales y varios ataques contra los grupos o miembros del grupo.
Idioma: Inglés
(visto en @BotsGram_cu)
#antispam, #protection, #management, #groups, #filter, #welcome
Some Buddhists serve as soldiers even though Buddhism teaches non-violence. Soldiers can protect people, and Buddhism considers the intention behind actions. Actions that reduce suffering can be acceptable according to Buddhist ethics. Concepts like karma and skillful action are important. International humanitarian rules guide soldiers to act carefully. Being a Buddhist does not always mean being completely against war. Martial arts like Kung Fu also connect to Buddhism. They teach discipline, self-control, mindfulness, and protecting others. The goal is training the mind and body, not just fighting.
🕉️⚔️🥋
[Read more]
@googlefactss
#Buddhism#Ethics#Soldiers#NonViolence#Karma#Protection#SkillfulAction#KungFu#MartialArts#Mindfulness