Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🛜🔠🔠🔠🔠🔠
🔠🔠🔠🔠
💛 Alkimyogar
Bu kitobni qancha kop maqtasam arziydi! Qayta qayta tinglang Va o'qing!
Va albatta barcha ORZU maqsadlaringiz Amalga oshganda bizni ham albatta tabassum bilan eslab qo'ying
🤍
🤍 SİZ SO'RAGAN AUDİO KİTOB!
#audiobook
💛@Biglibrary_uz
🔠🔠🔠🔠🔠🔠🔠🔠
🎙 Ichindagi ichindadur
💡 Hayrlı kun kitobsevar qadrdonlarim!! Sizga Juda zo'r
#audiobook🎧 bilan keldim.
Albatta tinglang! Juda ham zo'r kitob! Qancha tariflasam , shuncha so'zlar ojizlik qiladi! Ming marta maqtagandan ko'ra bir marta o'zingiz mazasini tatib koring 🫂
Bu kitobni o'qiganlar Yoki tinglaganlar bormi ,
🔥 reaksiyalarni bosib qoying
@Milliarderlarim
#Narratorr#Audiobook#amp#TTS
Join the Narratorr - Audiobook & TTS beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/Fv19nvDd
Shared by Dimitri
📖Title : The Frozen River
✍️Author : Ariel Lawhon
⭐️Rating : 4.38/5 (Goodreads)
📆Published : Dec 05, 2023
————————————————
Summary:The Frozen River by Ariel Lawhon is a historical mystery set in 1789 Maine. Midwife and healer Martha Ballard is called to examine the body of a man found trapped in the frozen Kennebec River. While authorities quickly declare the death an accident, Martha suspects something far darker. As she records events in her diary and follows the clues, she uncovers a web of violence, secrets, and injustice involving powerful members of the community. Determined to seek the truth despite threats and social pressures, Martha risks her reputation and safety while fighting for justice in a society where women’s voices are often ignored.
————————————————
#fiction#mystery#audiobook#historical#thriller#ariellawhon#thefrozenriver@Bookslibraryofficial
📖Title : More Days at the Morisaki Bookshop
✍️Author : Satoshi Yagisawa
⭐️Rating : 3.85/5 (Goodreads)
📆Published : Dec 06, 2011
————————————————
Summary:More Days at the Morisaki Bookshop follows Takako as she continues healing while living above her uncle’s secondhand bookshop in Tokyo’s Jimbocho district. Surrounded by books and familiar faces, she confronts lingering grief, evolving relationships, and quiet uncertainties about the future. The novel focuses on small, meaningful moments, showing how literature, routine, and human connection gently restore a sense of belonging. Through everyday interactions, it portrays healing as gradual, imperfect, and deeply tied to community, memory, and the comforting presence of books.
————————————————
#fiction#japan#cozy#audiobook#romance#moredaysatthemorisakibookshop#satoshiyagisawa@Bookslibraryofficial@free_novellas@eternalmantra
📖Title : Bemused
✍️Author : Farrah Rochon
⭐️Rating : 3.92/5 (Goodreads)
📆Published : Jan 07, 2025
————————————————
Summary:Five sheltered sisters living in a quiet seaside village learn that they are the legendary Muses, daughters of Mnemosyne, Goddess of Memory. After their mother is kidnapped by Hades, the sisters are forced to leave their protected lives behind. Guided by Calliope’s leadership, they journey through dangerous lands, face mythical trials, and uncover their divine powers. Along the way, they confront fear, doubt, and destiny itself. Through music, storytelling, courage, and unity, the sisters strengthen their bond and transform from overlooked performers into heroic figures, embracing their true identities and shaping their own legendary “gospel truth.”
————————————————
#fantasy#mythology#retellings#fiction#historicalfiction#audiobook#bemused#farrahrochen@Bookslibraryofficial@free_novellas@eternalmantra