Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Был бы у меня такой кот, я, может, и не женился бы никогда.
If I had a cat like that, I might never have gotten married.
• Может
[mo-zhyt]
Maybe, perhaps, probably, might
🔻This introductory word expressing possibility or probability is set off by commas in a sentence.
😉С пятницей, товарищи!
#just_a_joke
#just_cats
#punctuation
#Friday
😎 Stay with @learnRCRussian
Did you know that Spanish 🇪🇸 uses upside down exclamation and question marks (¡ and ¿) at the beginning of sentences?
¡Qué bonito! ("How beautiful!")
¿Cómo estás? ("How are you?")
Creo que tienes razón, pero ¿estás completamente seguro?
("I think you're right, but are you completely sure?")
Below you'll find a block of questions on these upside down punctuation marks.
For each question react with 👍🏻 if you got it right and 🙈 if you got it wrong.
@languagetrivia#question_block#punctuation
In the world of printing and journalism, the exclamation mark (!) has earned a variety of colorful nicknames. One of these humorous terms compares its shape to a specific part of a dog’s anatomy.
Sometimes an exclamation mark is humorously referred to as “a dog’s [what]"?
A) Tail 🐕
B) Nose 👃
C) Bone 🦴
D) C*ck🍆
Take the quiz below to find out
@languagetrivia#punctuation#symbol#slang
✏️Did you know about the Oxford comma, also known as the serial comma?
It's the final comma in a list of three or more items, placed before "and" or "or."
For example:
🔵I invited my parents, Taylor Swift, and Elon Musk.
Without the Oxford comma, it could look like this:
🔵I invited my parents, Taylor Swift and Elon Musk.
Wait, are my parents Taylor Swift and Elon Musk?! 😅
Not everyone agrees on its usage:
🟢Proponents argue it provides clarity and prevents ambiguity 📝
🟣Opponents feel it’s unnecessary in straightforward cases and takes up space 📰
For instance, the AP Stylebook often skips it unless absolutely needed, but the Chicago Manual of Style recommends using it in all cases.
Here are some examples showing how the Oxford comma can help fight ambiguity:
1️⃣Avoiding Misinterpretation:
I dedicate this book to my parents, Mother Teresa, and the pope.
Without the Oxford comma: I dedicate this book to my parents, Mother Teresa and the pope.
This could imply that your parents are Mother Teresa and the pope. 😳
2️⃣Clarifying Groupings:
We had coffee, cheese and crackers, and grapes.
Without the Oxford comma: We had coffee, cheese and crackers and grapes.
This could suggest that "crackers and grapes" are a combined dish. 🍇🧀
3️⃣Costly Consequences:
O'Connor v. Oakhurst Dairy (2017) was a U.S. legal case where truck drivers sued for overtime pay, challenging an ambiguous Maine law that lacked an Oxford comma. The law exempted work involving "packing for shipment or distribution" of goods.
Without a comma, it was unclear if "distribution" was part of "packing" or a separate activity. The court sided with the drivers, interpreting the ambiguity in their favor, leading to a $5 million payout. 💸
📌Ultimately, whether or not you use the Oxford comma is up to you, but the key is to be consistent. And it's also a good idea to use it in cases where it can help prevent ambiguity and misinterpretation!
Sources: Grammarly |Wikipedia
Tap ❤️ if you found this interesting
@languagetrivia#grammar#punctuation#fact