Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
[UZ] Bugun biz Xalqaro xotin-qizlar kunini butun dunyo ayollarining ajoyib yutuqlari va hissalarini keng qo’lamda nishonlaymiz. Keling, gender tengligini qo'llab-quvvatlashga, bir-birimizni kuchaytirishga va to'siqlarni birgalikda yengishga va'da beraylik. Va yana bir bor bu go’zallik bayrami bilan ayyolarimizni chin qalbdan tabriklaymiz
-
[EN] Today, we celebrate International Women's Day by honoring the incredible achievements and contributions of women around the globe. Let's pledge to support gender equality, empower each other, and break barriers together. Every step forward makes a difference.
-
[RU] Сегодня мы отмечаем Международный женский день, отмечая невероятные достижения и вклад женщин во всем мире. Давайте пообещаем поддерживать гендерное равенство, расширять возможности друг друга и вместе преодолевать трудности. Каждый шаг вперед имеет значение.
#InternationalWomensDay#Empowerment
Follow EUROUZ on Telegram: @eurouz_official
Web | Instagram | Facebook| Twitter (X) |LinkedIn
शिक्षा, कौशल विकास और उद्यमिता में भारी निवेश कर प्रधानमंत्री के नेतृत्व में केन्द्र सरकार #NorthEast के जनसामान्य का सशक्तिकरण कर रही है।
#YuvaShakti#Empowerment#YuvaShaktiForNE
📢 Listen Up, fellow Wolf pack!!! 🌍
🔴 Holy Shit! The truth about the exploitation of Africa's natural resources has finally been exposed. For years, America and France have shamelessly pillaged the riches of this continent, leaving its people in abject poverty. The dark secrets of child slave labor used to mine precious metals and gold have been unveiled.
🔵 But now, Africa has had enough! The tide is turning as the continent finds a new ally in Russia, a nation that respects their resources, values, and treats them as equals. Today, we witness the fall of France's colonial power in Niger, with politicians being stoned and luxury vehicles set ablaze.
⚠️ The situation in Niger has reached a boiling point, leading to the emergency evacuation of embassy staff by the U.S. State Department (fuck those guys), following the destruction of the French embassy by furious rioters.
🇷🇺 As the chaos unfolds, the Russian flags proudly waved among the crowds of demonstrators in Niamey reveal a glimmer of hope for Africa. The partnership between Africa and Russia signifies a new era, where African nations are determined to protect their resources and regain control over their own destiny.
🌍 The time for change has come. Let us stand in solidarity with the people of Africa as they assert their rights and demand justice. Together, we can ensure a future where exploitation is replaced with empowerment, and where Africa's wealth benefits its own people.
🔗https://www.dailymail.co.uk/news/article-12367511/Fears-Americans-trapped-Niger-State-Department-issues-emergency-evacuation-embassy-staff-French-embassy-torn-apart-rioters-Africa-country-meltdown-politicians-stoned-cars-torched-amid-brutal-military-coup.html
#Africa#Russia#Empowerment#Justice#StandTogether
"A Journey of Unawareness to Empowerment"
A 30-year-old entrepreneur thought breast cancer couldn't happen to her. But during a routine work training, she discovered a lump through self-examination. The diagnosis: stage 2 breast cancer.
Her journey transformed her into a beacon of hope. "Early detection is key," she'd say. "Don't assume you're immune. Take control of your health."
Join our Breast Cancer Day webinar on Oct 19th, 18:00 GMT+3:
- Breast cancer risk factors and prevention
- Early detection methods
- Latest research and advancements
- Support systems and resources
Zoom link: https://us06web.zoom.us/j/89636772918?pwd=J05Hz0r3iiZG9B3EPbzJFPq50pqDzH.1
#BreastCancerAwareness#Empowerment#EarlyDetection#HealingJourney
The government is empowering the #YuvaShakti of North East!
By investing in education, skills development & entrepreneurship, the government is unlocking the full potential of #NorthEast.
#YuvaShakti#Empowerment
#YuvaShaktiForNE
Uzbekistan has made a historic leap in the Gender Equality and Governance Index, rising 51 positions, from 103rd to 52nd place!
This success shows real progress in women’s education, economic empowerment, and the growth of innovative IT initiatives.
We’re committed to increasing women’s participation in the IT sector. Our educational programs aim to ensure that every woman can thrive, benefiting from the accessible public services created by the state.
Uzbekistan is a country full of talented youth, and our ambitious, creative girls are at the forefront. Empowering young women in tech is a source of national pride.
By breaking down barriers, we’re opening doors for women to lead in technology. With talent, creativity, and determination, there are no limits to what can be achieved!
This achievement reflects the power of teamwork. Thanks to international organizations, private companies, and local initiatives, Uzbekistan is building an inclusive IT ecosystem driven by diversity.
Supporting women in tech is an investment in the future—one that benefits everyone.
While progress has been made, we know there’s more to do. Women remain underrepresented, especially in rural areas. We’re working to boost computer literacy and provide technology access for rural women.
Our Vision: Every woman should have the opportunity to reach her potential, be well-educated, and equipped to earn a living—maybe even lead the next tech unicorns!
By 2030, under the Digital Uzbekistan Strategy, we aim for 300,000 IT specialists, with women making up at least half of them.
Together, we can build an inclusive, innovative future, where every girl and woman can shape the digital world.
Join us in this mission! We welcome international organizations, private companies, and individuals to collaborate in empowering girls in STEM and STEAM fields.
Let’s continue working to ensure equality and diversity in every corner of Uzbekistan!
#Uzbekistan#WomenInTech#Inclusion#STEM#Innovation#Empowerment
🎤 Great news! 🌟 We are excited to announce the launch of our new public speaking course at ADC! 🏫
If you want to overcome the fear of public speaking, improve your presentation skills, or simply become a more effective communicator, our course is designed for you. With experienced instructors, a supportive environment, and a program focused on real-life success, we are here to help you find your voice and make an impact.
👩🏫👨🏫 Join us on a journey of development, confidence, and empowerment. Classes are starting soon, and spaces are limited, so book your spot today!
☎️For more details:
74 2261078
74 2281121
74 2281666
74 2276163
74 2252536
#PublicSpeaking#FindYourVoice#Empowerment#CommunicationSkills#Education#NewCourse#JoinUs