Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
📝 INTERVIEW | Feminism and Revolution: A Conversation with Alejandra Laprea
In the latest VA interview, Alejandra Laprea, a popular feminist and member of the World March of Women, discusses how popular feminism in Venezuela continues to shape the revolution from the ground up. She stresses the importance of unity within the feminist movement, advocating for a collective, consensus-based agenda.
"We are experiencing a moment of setbacks at the global, continental, and national levels. In Venezuela, the feminist movement must come together and build a common agenda – one that is truly collective and based on consensus, rather than a mere compilation of different perspectives." States Alejandra.
🔗 Read the full interview here: https://shorturl.at/ppCss
#Feminism#Sanctions#WomensRights
🗒️🗣️ INTERVIEW | Aimee Zambrano: ‘Let Us Demand a Justice System with a Gender Perspective’
In the latest VA interview, activist and researcher Aimee Zambrano takes stock of gender violence in Venezuela and the necessary state policies to respond.
Through the Utopix Femicide Monitor, a platform that collects cases from open sources, Zambrano and her team have tracked patterns since 2019. However, Zambrano warns that other forms of violence are increasing, particularly attempted femicides, sexual abuse, and cases linked to the disappearance of women and girls.
She also argues that Venezuela needs a justice system with a gender perspective and a coordinated state response involving multiple ministries, including education, housing, and communication, to address gender violence.
Read the full interview here 👉🏾https://shorturl.at/tCbzV
#Feminisms#WomensRights
On 7 November 1800, Paris required women to get police permission to wear pants — keeping them from wearing pants without authorization.
[Read more here]
@googlefactss#pants#womensrights#law#France
🇿🇦"You Strike a Woman, You Strike a Rock"
Today is National Women’s Day in South Africa.
🗓 On August 9, 1956, a protest march was held in Pretoria against the extension of the humiliating Pass Laws to black women — apartheid-era regulations requiring all black South Africans to carry a “dompas” containing their personal details and movement permits.
✊ The march was led by four courageous women: Helen Joseph, Rahima Moosa, Sophie Williams, and Lillian Ngoyi. A monument in central Pretoria now honors their legacy.
📌 The slogan "You strike a woman, you strike a rock" became a powerful emblem of women’s strength and resilience: oppression only solidifies their resolve.
#SouthAfrica#NationalWomensDay#PassLaws#Apartheid#Pretoria#WomensRights#History
Female genital mutilation (FGM) also misleadingly known as "female circumcision" removes and injures parts of the female genitals for non-medical reasons. It is usually performed on girls from infancy to age 15. It has no health benefits and can cause severe pain, heavy bleeding, infection, shock, infertility, childbirth complications, and psychological trauma. Over 230 million women and girls worldwide have undergone FGM.
No religion requires or asks for this practice.
🚫✂️👧🌍⚖🪧
Warning, the link and information about this is not for the faint of heart. Research about this might be disturbing to some people.
[Read more at your own discretion]
[Poll about your opinions]
@googlefactss
#facts#humanrights#health#womensrights#education#globalissues#childabuse
Mojtaba Khamenei became Supreme Leader of Iran after his father, Ali Khamenei, was killed in a U.S.–Israeli airstrike. He leads with hard-line policies, controlling the military, security forces, and political decisions. For ordinary Iranians, this means strict government control, limited political freedom, limited internet, harsh enforcement of laws, and continued tensions with the West. Daily life and dissent will likely remain tightly restricted under his rule.
🕌🇮🇷⚔️
[Read more]
@googlefactss
#Iran#MojtabaKhamenei#SupremeLeader#politics#newsfacts#freeIran#protests#womensrights