Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Lutfullo Tagoev, Smart Hub asoschisi va bosh direktori, post-COVID davrida paydo bo‘lgan g‘oyadan AI asosidagi onlayn ta’lim platformasi qanday tez rivojlanganini aytib beradi.
Smart Hub odamlar va kompaniyalarga moslashtirilgan o‘quv dasturlarini yaratishda qanday yordam berishini, biznesni tez o‘stirish va O‘zbekiston bozoriga akseleratsiya dasturi orqali kirish tajribasini bo‘lishadi.
DSA asosida IT Park Ventures tomonidan $50,000 miqdorida investitsiya taqdim etildi.
—
Lutfullo Tagoev, Founder & CEO of Smart Hub, shares how an AI-powered e-learning marketplace evolved from a post-COVID idea into a fast-growing international startup.
He explains how Smart Hub helps individuals and companies build custom training programs, scale revenue, and enter new markets, including Uzbekistan, through acceleration support.
An investment of $50,000 was provided under the DSA by IT Park Ventures.
Telegram | Instagram | Facebook | Youtube | LinkedIn
#interview
Oneplace.HRasoschisi Xurelbaatar Bat-Orshix sun’iy intellekt va geymifikatsiya ishga qabul qilish va moslashishni qanday o‘zgartirayotgani, an’anaviy testlarni almashtirayotgani, HR vazifalarini avtomatlashtirayotgani va xodimlarni ushlab turishni kuchaytirayotganini gapirib berdi.
🏆 Xurelbaatar Bat-Orshix «Digital Startup Awards» dasturining “Akseleratsiya” trekida ishtirok etgan.
Bugungi kunda u O‘zbekistonda ofis ochib, DSA dasturimiz orqali mamlakat bozoriga kirib kelgan loyiha sifatida faol rivojlanmoqda.
🚀 Shuningdek startap O’zbekistonda kengayish uchun IT Park Ventures fondidan 50 000 dollar sarmoya jalb qildi.
—
Oneplace.HRfounder Khurelbaatar Bat-Orshix spoke about how artificial intelligence and gamification are changing recruitment and adaptation, replacing traditional tests, automating HR tasks, and strengthening employee retention.
🏆 Khurelbaatar Bat-Orshix participated in the "Acceleration" track of the "Digital Startup Awards" program.
Today, it is actively developing as a project that has opened an office in Uzbekistan and entered the country's market through our DSA program.
🚀The startup also attracted $50,000 from the IT Park Ventures Fund to expand in Uzbekistan.
Telegram | Instagram | Facebook | Youtube | LinkedIn
#interview
Born in Samarkand and educated in South Korea and the United States, Sanjar Atamuradov is now building one of Silicon Valley’s most ambitious humanoid robotics platforms — Humanola. The startup uses telepresence to enable real-time robot control and transform human interactions into the training data required for physical AI.
In his interview with IT Park Uzbekistan and The Tech, Sanjar discusses his journey from Samarkand to KAIST and Georgia Tech, the launch of Humanola after raising $2.5 million, and how the company addresses critical challenges in robotics by providing unified infrastructure for teleoperation and large-scale data generation.
📖 Read the full article to learn more: outsource.gov.uz
Telegram | Instagram | Facebook | Youtube | LinkedIn
#interview
Samarqandda tug‘ilib, Janubiy Koreya va AQSHda ta’lim olgan Sanjar Atamuradov bugun Kremniy vodiysidagi eng ambitsiyali gumanoid robototexnika platformalaridan biri — Humanola’ni yaratmoqda. Startap teleishtirok texnologiyasi orqali robotlarni real vaqt rejimida boshqarish va inson harakatlarini jismoniy sun’iy intellekt uchun zarur o‘quv ma’lumotlariga aylantirish imkonini beradi.
IT Park Uzbekistan va “The Tech” bilan intervyuda Sanjar o‘zining Samarqanddagi bolalikdan boshlab KAIST va “Georgia Tech”gacha bo‘lgan yo‘li, $2,5 mln investitsiyadan so‘ng “Humanola”ning ishga tushirilishi, shuningdek kompaniyaning teleoperatsiya va katta hajmli ma’lumotlar ishlab chiqarish uchun yagona infratuzilma taqdim etish orqali robototexnikadagi muhim muammolarni qanday hal qilayotgani haqida so‘zlab berdi.
📖 Batafsil ma’lumot uchun to‘liq maqolani o‘qing: it-park.uz
Telegram | Instagram | Facebook | Youtube | LinkedIn
🔺 “This is the naivete of our European leaders”
Former Italian ambassador Elena Basile expresses concern that Europe is backing violations of international law and regime changes, highlighting the naivety of its leaders.
Watch in full
#Interview
@PresstvPrograms
🔺"European Parliament is far away from the European people"
Elena Basile highlights the gap between the European Parliament and its citizens while criticizing its stance on regime changes in Iran and Russia.
Watch in full
#Interview
@PresstvPrograms
🔺According to Former Italian ambassador Elena Basile, while Western diplomats are aware of the reality of Western hegemonic policies, they apply a form of self-censorship, because, as members of the diplomatic corps, they cannot contradict their governments.
Watch in full
#Interview
@PresstvPrograms
🔺“We face a Western hubris without limits.”
Former Italian ambassador Elena Basile says the wars from Iraq to Ukraine and Gaza reflect a long-running US-led imperial policy backed by Europe.
Watch in full
#Interview
@PresstvPrograms
🔺“We should restore confidence and respect international law.”
Belarusian deputy foreign minister Igor Sekreta says the international order is damaged but not destroyed, arguing that restoring trust, respect for international law, and new confidence-building mechanisms is the only path forward.
#Interview
@PresstvPrograms
🔺“Illegal migration is a problem that we could combat only together.”
Belarusian deputy foreign minister Igor Sekreta says Belarus does not use migrants as leverage, stressing that illegal migration stems from hardship in countries of origin and must be addressed jointly through humane procedures and cooperation.
#Interview
@PresstvPrograms
🔺Minsk conference promotes Eurasian security dialogue
Igor Sekreta says that continuous dialogue through inclusive formats, such as the Minsk conference, helps reduce misunderstandings, build awareness, and support Eurasian security without replacing existing international organizations.
#Interview
@PresstvPrograms
🔺Igor Sekreta says that the erosion of the Helsinki spirit, NATO expansion, and the collapse of the post–Cold War security architecture have weakened trust, which diplomacy must now restore.
#Interview
@PresstvPrograms