Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Hello everyone!
Our guest speaker for today is sick, so Today, we will have a shorter version of our weekly 19:00 chat session. It will be solely focused on YOUR questions to us. Let’s practice your English!!! 💬🇺🇸
We are looking forward to connecting with you in 15 minutes!
#SPEAKENGLISH#QandA
🦵 Here are 5 English phrasal verbs with ‘kick’ for you. Kick back and read them and then have a go at the quiz – and see if you can use any of them in a sentence of your own! (Images: Getty)
#vocabulary#speakenglish#englishtips
We are super excited for you to meet our friend, Bekzod Kholmurodov, an Uzbekistan-born sophomore student at Drexel University, USA this Saturday, at 19:00 Tashkent time! Don’t miss this unique opportunity to learn from someone who has an invaluable experience of coming to the US as an international high school student first, and now is a college student as a El-Yurt Umidi scholar!
Invite your friends and get your questions ready!!
#UzbeksInAmerica#SpeakEnglish#OneStepAtATime
🇺🇸🤝🇺🇿
🥊 There are quite a few English phrasal verbs with ‘hit’ – here are 5 of them to learn and use. 👋 Have a go at the quiz – and see if you can use any of them in a sentence of your own! (Images: Getty)
Extra: Click on our link in bio to learn 4 phrases with 'hit'.
#learnenglish#vocab#vocabulary#speakenglish#englishtips
Let’s be real: You’ve probably seen a list like this 1,000 times. It looks repetitive, maybe even "dumb." But here is why it actually matters for you:
When you only have one word for everything (like "Good"), your brain "glitches" when you're trying to speak fast. You hesitate because you're searching for variety but your "vocabulary folder" is empty. 🧠
The Secret to Speaking Fast:🛫
Fluency isn't about knowing the hardest words; it's about having options. When you have 3-4 ways to say the same thing, your brain doesn't have to stall. It just picks the next available word and keeps the flow going.
-
#English#SpeakEnglish#EnglishTips#Vocabulary#SpokenEnglish
Group: English Chatting House | Global English Speaking Chat
Members: ~4.48K
💢 Username: @english_chatting_house
Description:
⭐ Welcome to ECH! English only - global English chat, spoken English practice, fun talks & chill worldwide vibes. Talk English, meet international people, improve fluency, keep it clean. No beef, no hate, no promo. Got any queries? :- @Bilxerian
🏷 Tags: #languages
#learnenglish#englishchat#speakenglish#englishgroup#globalchat
https://telegramchannels.me/groups/english_chatting_house
Idiom of the Day!
🚌 Throw someone under the bus
Meaning: To blame someone else so you don't get in trouble.
Example: "Mark made the mistake, but he threw me under the bus!" 😠
#LearnEnglish#EnglishIdioms#Vocabulary#ESL#EnglishPhrases#SpeakEnglish
Do you know someone who always thinks that everyone else has a better life than them?! 🙄😅 Scroll through the images to find out how to use ‘the grass is always greener on the other side’ 🌱, and don’t forget to answer the questions on the last slide!
EXTRA: Could walking 7,000 steps a day could improve your mental health? 🚶 Click the link in our bio to find out and learn some useful vocabulary in the process! 📰💚
Image: Getty
#vocabulary#learnenglish#englishlanguage#expression#idiom#proverb#englishclass#speakenglish
You know when somebody just WON’T change their ways? 😠 We’ve got an English expression for that! ✅
Scroll through the images to find out how to use ‘You can’t teach an old dog new tricks.’ ❌🐶
Can you use it in a sentence – and do you have a similar expression in your language? 👇👇👇
MORE: If you'd like to learn some more animal idioms, like 'rabbit on 🐰' or 'as sick as a parrot 🦜', click the link in our bio!
Image: Getty
#trick#proverb#learnenglish#vocabulary#learnenglish#englishlanguage#expression#idiom#englishclass#speakenglish
Here are 5 linkers that you can add to your conversation to make it flow better and sound more fluent!
1) To be honest – I’m going to give my opinion (even if it’s insulting!)
2) Actually – to correct information or say something surprising
3) Mind you – I’ve just thought of something that contrasts what I was saying
4) By the way – I’m going to introduce a new topic I’ve just remembered
5) Anyway – I’m going to finish the conversation or change topic now
Add them to your conversations to help them flow! Which one is your favourite?
#learnenglish#speakenglish#vocabulary#bbclearningenglish#britishenglish#formalenglish#linkers#naturalenglish#nativespeakerenglish#conversationskills#ncoversationalenglish
🚀 Power up your English vocabulary with these FIVE phrasal verbs with ‘pay’! Take a look 👀 and then practise using them right now in the comments! 🤔 Do you know any more phrasal verbs with ‘pay’?
(Images: Getty)
🎧 Click on the link in our bio to listen to Neil and Georgie talk about money!
#phrasal#phrasalverb#pay#payoff#payout#payup#payfor#learnenglish#vocab#vocabulary#speakenglish#englishtips