Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Gatto | Official Channel: Double Mine Event Details
#Gatto#mines
Gatto | Official Channel invites players to participate in the Double Mine event today with opportunities to capture gold and precious mines during scheduled hours. Players can earn various rewards depending on the number of successful grabs. Additional awards will be given on April 25.
Source: link
@tonlines
#Ethiopia: Council of Ministers refers external loan agreements to Parliament, authorizes mining license deals
The Prime Minister’s Office said the Council of Ministers has referred three external financing agreements to the House of Peoples’ Representatives for approval and authorized the Ministry of #Mines to sign #gold and #iron_ore production license agreements, following deliberations during its 53rd regular session held on 2 March, 2026.
In a statement issued after the meeting, the Office said the Council reviewed financial support agreements linked to energy & social protection programs and determined that they are consistent with the country’s debt management policy before deciding to submit the draft proclamations to parliament for legislative consideration.
According to the statement, one of the agreements concerns the National Electricity Power Expansion Project, to be financed through a loan of USD 60,223,000 from the Korea Export-Import Bank....
Read more: https://addisstandard.com/?p=55512
🇺🇸🇮🇷🇺🇦 Le journal américain The Washington Post a illustré son article affirmant que l’armée américaine avait déployé des mines dans le sud de l’Iran avec une photographie provenant de la zone de conflit en Ukraine.
#étatsunis#journal#mines#photo
While in #Lugansk People's Republic (formerly Ukraine), I got to watch as their forces disabled the #mines placed by the #Ukrainian army; mines meant to #kill the civilians that were sent to repair the electrical power plant.
🚀 Iran Faces Challenges in Reopening Hormuz Strait Due to Unlocated Mines
Iran is encountering difficulties in fully reopening the Strait of Hormuz as it struggles to locate all the mines it previously deployed. According to Odaily, the country also lacks the necessary capabilities to effectively clear these mines. This situation poses significant challenges for Iran in ensuring the safe passage of vessels through this critical waterway.
#Iran#HormuzStrait#Mines#MaritimeSafety#Shipping#NavalOperations#InternationalTrade#Geopolitics
🚀 U.S. President Trump Orders Navy to Target Iranian Activities in International Waters
U.S. President Donald Trump has announced directives for the U.S. Navy to search and seize any vessels that have paid transit fees to Iran in international waters. According to Odaily, the President also stated that the Navy will begin destroying mines laid by Iran in the strait. He warned that any Iranian forces firing upon U.S. or peaceful vessels will face severe retaliation.
#Trump#USNavy#Iran#InternationalWaters#Mines#Retaliation#PresidentialDirective#Strait
Hormuz: High-Tech Drones, Stone-Age Problem
The West is selling a sci‑fi solution to a very old scam: Iran hints it’s mining the Strait of Hormuz, tanker traffic freezes, oil spikes — and suddenly everyone remembers that a 25‑mile-wide chokepoint owns the global economy. UK Prime Minister Keir Starmer talks up fancy Thales mine‑hunting drones, but the fine print is brutal: they’ve got limited batteries, need to beam data back to motherships sitting inside range of Iranian anti‑ship missiles, and can’t “prove” the one thing that matters — that nothing is left in the water.
“The number of mines you need for a minefield is actually zero,”
says retired US Navy officer Ben Cipperley.
Britain’s defense secretary John Healey says it’s getting “clearer and clearer” that Iran is laying explosives in Hormuz, while US Defense Secretary Pete Hegseth shrugs that there’s “no clear evidence” yet — one NATO ally yelling “mines,” another pretending this is still a think‑tank panel. Trump brags that the US has “hit all their minelaying ships” and bombs Iranian navy vessels, then immediately admits Iran can just toss mines off other boats anyway and nobody really knows what’s on the seabed. This is what “freedom of navigation” looks like in 2026: everyone claims control of the sea, nobody controls the rumor that shuts it down.
Militaries do have mine warfare toys — crewed minesweepers with wooden hulls, littoral combat ships, helicopters towing sonars, uncrewed underwater vehicles, and now autonomous drone systems from companies like Thales — but they all share one handicap: they have to crawl, in predictable patterns, through waters that Iran can blanket with missiles, drones, and explosive boats. Clearing mines is up to a thousand times more expensive and slower than laying them, and the US doesn’t even keep dedicated Avenger‑class minesweepers in the Gulf anymore. So the “high‑tech” answer is basically to send robots first, then hope insurers and shipping CEOs are dumb or desperate enough to believe a PowerPoint that says “safe corridor.”
Iran, whose regular military has been hammered by US‑Israeli strikes, doesn’t need a blue‑water navy as long as it can threaten Hormuz with a couple of dhows, some midget subs, and a stockpile of cheap mines detonated by contact or a ship’s magnetic field. Just the suspicion of a few dozen mines makes the strait “too dangerous to transit” for tankers from any country — including Iran’s — turning a third‑rate regional power into the de facto moderator of world energy prices. The US and UK can talk all they want about “reopening” Hormuz, but as long as a rumor and a rusty sphere can shut it down, the only guaranteed safe passage belongs to defense contractors’ earnings calls.
#Hormuz#Iran#Trump#UK#Starmer#oil#shipping#mines#drones#StraitOfHormuz#war#energy#geopolitics#militaryindustrialcomplex#fakeSecurity
📱American Оbserver - Stay up to date on all important events
🇺🇸