Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🚀BeforeCoinMarketCap Team is pleased to announce the first AIRDROP of BCMC1 Token 🚀
🏆 Reward for #Airdrop: 2,000 BCMC1 ($20) ➕ 250 BCMC1 ($2,5) ref ➕ 200 BCMC1 ($2) send announce
🏆 Reward for #Bounty: Up to 35,000 BCMC1 (~$350)
🔛 Airdrop Google Form for BeforeCoinMarketCap
🌐OFFICIAL CHANNELS:
Telegram
Twitter
Facebook
Instagram
LinkedIn
YouTube
Website: beforecoinmarketcap.com
BeforeCoinMarketCap
💰 Reward for #Airdrop: 2,000 BCMC1 ($20) ➕ 250 BCMC1 ($2,5) ref ➕ 200 BCMC1 ($2) send announce
💰 Reward for #Bounty: Up to 35,000 BCMC1 (~$350)
🖥 Fill the form:
https://docs.google.com/forms/d/1MbhzJpK1ikAWitHHjnekfrKY3ZQ8_Y147nCqqEqtjq4/edit
☝🏻Join the telegram chat
☝🏻 Follow our twitter page and retweet the pinned post.
BeforeCoinMarketCap is a platform for tracking initial placement of tokens, and audit of valid tokens with small volume. Our platform rewards users of valuable information and tokens of own ecosystem tokens. Visit beforecoinmarketcap.com for more details
🚀BeforeCoinMarketCap Team is pleased to announce the first AIRDROP of BCMC1 Token 🚀
🏆 Reward for #Airdrop: 2,000 BCMC1 ($20) ➕ 250 BCMC1 ($2,5) ref ➕ 200 BCMC1 ($2) send announce
🏆 Reward for #Bounty: Up to 35,000 BCMC1 (~$350)
🔛 Airdrop Google Form for BeforeCoinMarketCap
🌐OFFICIAL CHANNELS:
Telegram
Twitter
Facebook
Instagram
LinkedIn
YouTube
Website: beforecoinmarketcap.com
SIX MILLION DOLLAR payout just went to the whitehat named pwning.eth for finding a critical vulnerability in Aurora, making it the second-largest #bounty on record 👏🏼
No user funds were lost, and #Aurora quickly patched the bug, leading to a positive outcome for everyone 🎉
Read our #Bugfix Review ⬇️
https://medium.com/immunefi/aurora-infinite-spend-bugfix-review-6m-payout-e635d24273d
To the beautiful and wonderful BeforeCoinMarketCap Community!
Sincerest wishes for health, happiness, and peace during this Holidays season and throughout the coming year! We thank you all for your unlimited contribution. We hope you stay with us, there are many interesting things this coming year!
Let the spirit of love gently fill our hearts and homes. In this loveliest of seasons may you find many reasons for happiness.
From all of us at BeforeCoinMarketCap. 💝
#BCMC1#BeforeCoinMarketCap#Crypto#BCMCToken#Airdrop#Bounty
💧BeforeCoinMarketCap BOUNTY💧
(For 100 participants only💯)
Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content.
Example: Please watch this videos for instructions: https://youtu.be/8t1ucZFnyL8 & https://youtu.be/aYrpgGpI074
1 Best video will receive 15,000BCMC1 ($200) and will posted on our social channels.🏆
Mandatory:
✅Describe the People IEO. (Community voting)
✅Describe the People IEO. (Participant projects)
✅Explain the MLM system (Ongoing token sales)
❗️Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given.
#BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#bounty#Bounty
💎 BeforeCoinMarketCap New BOUNTY 💎
For 100 participants only💯
Bounty Tasks✅
Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content.
📍Mandatory:
1. Describe the search window.
2. Describe the Announcement window
3. Explain the MLM system (Ongoing token sales):
4. Describe the promotion website
Best video will receive 20,000BCMC1 ($300) and will posted on our social channels.
📍Bounty Google Form
Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given.
#BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Bounty
#python#bounty#bugbounty#bypass#cheatsheet#enumeration#hacking#hacktoberfest#methodology#payload#payloads#penetration_testing#pentest#privilege_escalation#redteam#security#vulnerability#web_application
Payloads All The Things is a comprehensive collection of useful payloads and bypass techniques for web application security testing and penetration testing. It offers detailed documentation for each vulnerability, including how to exploit it and ready-to-use payloads, plus files for tools like Burp Intruder. You can contribute your own payloads or improvements, making it a collaborative resource. It also links to related projects for internal network and hardware pentesting, and provides learning resources like books and videos. Using this resource helps you efficiently find and test security weaknesses in web applications, improving your pentesting effectiveness and knowledge.
https://github.com/swisskyrepo/PayloadsAllTheThings