Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Коллекция Louis Vuitton FW24 от Pharrell 👨🌾
На подиум перенесены мотивы кантри и вестерн.
Благодаря технике вышивки в коллекции подчеркнута ключевая иконография американской одежды в стиле western.
Разрабатывая тему американского вестерна и рабочей одежды Louis Vuitton сотрудничали с художниками народов Dakota и Lakota в создании аксессуаров , а также над постановкой шоу и саундтреком.
От ковбойских шляп до кожаных кепок и перчаток, украшенных пряжками и драгоценными камнями, олицетворяющих "прерийного" денди - стиль был выдержан до конца!
Показ озвучили исполнители из группы Native Voices of Resistance.
#western
🍿 'Eddington': Joaquin Phoenix and Pedro Pascal ignite chaos in Ari Aster’s explosive new thriller
📆Release: July 18, 2025
🎭Genre: #Thriller · #Western
🍿Follow Movie
Ari Aster ('Hereditary', 'Midsommar') dives headfirst into the madness of 2020 with 'Eddington', setting Joaquin Phoenix ('Joker') as a small-town sheriff on a collision course with Pedro Pascal ('Gladiator II'), the charismatic mayor. Set during the peak of pandemic paranoia and simmering social unrest, this modern western thriller promises to escalate from small-town drama to something far darker—mysterious murders, hidden agendas, and neighbors turning against each other. 🏜🔥
With the compelling duo joined by Emma Stone ('La La Land') and Austin Butler ('Elvis'), there's no doubt this will be Aster’s most unsettling, gripping, and probably mind-bending film yet. My gut says: expect psychological twists, chilling confrontations, and a portrayal of America at its breaking point. Brace yourselves—it's about to get weird. 💥😬
#western#Filmscore
Music from Ennio Morricone "The Ecstasy of Gold"
This music from the film "The Good, The Bad and the Ugly" plays when Tuco is searching a graveyard for a graveyard that holds 200 000$ worth of gold. It encompasses the gold fever of the wild west.
This music as the film holds a part of the European spirit in it. Discover, explore, go where none has dared. Create something beautiful that will last.
RIP Ennio Morricone
https://youtu.be/PYI09PMNazw
🍿 ‘Eddington’: Ari Aster’s COVID Western We Never Saw Coming
📆Release: July 18, 2025
🎭Genre: #Western · #PoliticalDrama · #Thriller
⬇️Follow Movie
Joaquin Phoenix (‘Joker’, ‘Beau Is Afraid’) and Pedro Pascal (‘The Last of Us’, ‘The Mandalorian’) go head-to-head in a political showdown packed with conspiracy theories, protest flashbacks, and machine-gun chaos. ‘Eddington’ marks Ari Aster’s boldest pivot yet — turning the madness of 2020 into a surreal, explosive Western with private jets hovering over the desert and six-foot-apart standoffs.
It dives straight into the post-George Floyd unrest with sharp satire and dark humor, escalating from tense debates to all-out gunfire. Aster may have stepped out of horror, but the discomfort is still razor-sharp. Phoenix is electric, and yes — Pedro is everywhere, but in this one, he absolutely earns it. 🧨🗳🤠
“Western Sanctions Have No Impact On the Russian Economy”
Western sanctions are not having a “significant impact” on the Russian economy, the EU’s sanctions envoy has said, ahead of the fourth anniversary of Moscow’s full-scale invasion of Ukraine.
David O’Sullivan, a veteran Irish official, said sanctions were “not a silver bullet” and would always face circumvention, and insisted that after four years he was confident they were nit having a real effect.
“I am fairly bullish. I think that the sanctions have not really had a significant impact on the Russian economy,” he told the Guardian in a rare interview.
We may be, in the course of 2026, coming to a point where the whole thing becomes unsustainable, because little of the Russian economy has been distorted by the building up of the war economy at the expense of the civil economy.”
O’Sullivan was speaking after weeks of intense Russian attacks on Ukraine’s energy infrastructure as the country endures a bitterly cold winter, with temperatures in Kyiv plunging to -20C this week.
Ukrainian counterparts, he said, had told him that Russia had been able to launch twice as many drones and missiles last month compared with January 2025.
Putin’s war machine has not come without a cost to the wider economy, which is thought to be under its greatest strain since the early days of the war.
Oil revenues are plummeting, inflation is running at about 6% and interest rates at 16%.
O’Sullivan, who has more than four decades’ experience in the EU institutions, was appointed EU special envoy for sanctions in December 2022 with a remit to counter their evasion and circumvention.
But China, with its “no-limits” friendship with Moscow, was an exception.
“China is clearly sort of backfilling and providing support” to Russia, although not in the form of direct military equipment supplies, he said.
Several EU leaders had raised this concern with Beijing, he said. “The answer is always the same: ‘Nothing to see here. We don’t know what you’re talking about. We don’t see any problem.’”
#western#sanctions#impact#economy
📱American Оbserver - Stay up to date on all important events
🇺🇸
Colonization of Africa
#Belgian soldiers holding a #Somali child above a fire roasting him alive in Mogadishu! 1993
#Western
https://t.me/YediotNewsChat