Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#Germany
🦇 A €200 million railway section in Germany is stalled because of bats
In Baden-Württemberg, residents of the Calw district are waiting for train traffic to resume on a railway section and tunnel whose repair took decades and cost over €200 million. But there is one insurmountable obstacle — more than 1,000 bats living in the tunnel between Calw and Weil der Stadt stations.
These animals are under strict protection, so they cannot be removed. An unusual solution was found — to build a protective concrete wall inside the tunnel. On one side, trains will run; on the other, the bats can sleep undisturbed.
This will require 300 concrete blocks and about €80 million. Additionally, ultrasonic sensors will be installed to help the bats navigate their new shelter. However, it is still unknown how quickly they will adapt to the new structure, and this will determine when the tunnel can reopen.
⚠️ This is not an isolated case: in Kiel, 900 bats prevented the demolition of an old swimming pool because the animals refused to move to new shelters.
🦇 Sometimes even very small creatures can have a big impact on massive infrastructure projects!
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
🇩🇪#Germany: Men in Germany aged 17 to 45 are required to obtain approval from the Bundeswehr (German armed forces) career center before leaving the country for more than three months, whether for study, work, or travel.
The provision was included in a broader military reform package approved in December, but went largely unnoticed until it was reported by the German outlet Frankfurter Rundschau. The measure received little public attention at the time and was not widely discussed.
Despite the law being in place, it remains unclear how this requirement will be implemented in practice, particularly for individuals who were unaware of it or who have already left the country.
"We cannot remain silent. No-one can remain silent when there is an ongoing genocide and when people are denied the most basic human needs ... To stand with Palestine is to be human."
Greta Thunberg calls out Israel's genocide during a speech in Leipzig, #Germany.
https://t.me/YediotNewsChat
Heidelberg, #Germany🇩🇪
Heidelberg was not affected by the bombing of the Second World War, so it was preserved in its original medieval form - a castle, numerous churches and abbey, ancient streets.
Nuremberg, #Germany🇩🇪
Every year in Nuremberg, the largest Christmas fair is held throughout Europe.
Nuremberg is the city of inventors. It was he who gave the world things such as pocket watches, a globe, a compass, a pelting and a current machine.
🇩🇪#Germany: A knife attack took place during an anti-Iranian regime protest in Hamburg.
A man went on a stabbing spree targeting protesters, reportedly deliberately targeting anti-regime demonstrators. He managed to stab two protesters. One victim is in serious condition in hospital, while the second received medical aid at the scene after being stabbed in the leg.
(via @froopashee2)
Repost via @ben_ditto on IG
🇩🇪#Germany: Cockroach swarm agents 🪳
Swarm Biotactics, a deep tech start-up based in Kassel, Germany, specialising in “bio-robotics”: putting miniature sensor backpacks on cockroaches and then sending these as swarms into environments inaccessible for conventional robots, drones, or humans such as collapsed structures following natural disasters, GPS-denied areas, or contested warfare zones. The swarm of roaches act as real-time data agents 🪳 The company has received €13 million in funding so far from a consortium of international investors, including Vertex Ventures US, Possible Ventures, and Capnamic 🪳
Footage of cockroaches taken from 60 Minutes on CBS.