Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
#video#Arctic
On the 80th parallel north, there’s not much life. It’s a vast icy desert with the occasional polar bear in the distance. Nevertheless, Russian researchers have been travelling nearly to the top of the world since 1937 to collect data from the Arctic region.
They used to land on an old thick ice floe to live and work on it for almost a year. Then, they slowly drifted across the Arctic ocean. But warmer temperatures mean the ice cover is melting rapidly. So expeditions had to be evacuated after the ice gave way under their drifting stations.
They’ve come up with the ‘ship and ice’ polar station when researchers work on the ice but can retreat to the safety of a vessel. We joined an expedition aboard the Akademik Tryoshnikov.
Follow: https://t.me/rtdocumentary
Have you ever wanted to go to the Arctic?
#video#Arctic
RT’s Konstantin Rozhkov travelled to the North Pole on a giant Russian nuclear-powered icebreaker to film the fascinating landscapes of one of the most beautiful but one of the riskiest places on our planet.
Swimming in the icy waters of the Arctic Ocean and meeting a polar bear are just a few thrilling experiences he had there!
However, a journey to the North Pole is not only about fun and beautiful views. It’s also about strong swell, extreme weather conditions, the polar day insomnia, and the complete absence of any communication services.
How did Konstantin and his crew deal with their hardships? Watch North Pole: Inside a Russian Nuclear Icebreaker to find out!
Follow: https://t.me/rtdocumentary
#photo#Arctic
Did you know that at up to three meters, Arctic ice is so thick that ships can’t pass even following an icebreaker? That’s why icebreakers like Taymyr have to pull them with steel tow lines.
RT Documentary’s Natalya Kadyrova is on board the Taymyr icebreaker once again. Taymyr is giving her crew a ride to another vessel, Sibir, in the Kara Sea. The captain of Taymyr is Natalya’s old friend. When she first filmed in the Arctic nine years ago, he was chief mate. ‘It’s funny to find yourself again on this charming ship after so many years and so many vessels,’ Natalya says.
‘Not far from the icebreaker are fishermen. Fishing for smelt is underway - they can’t be disturbed. Plus, they’re used to icebreakers. There are many vessels these days. Apparently, there will be more soon.’
For more about the icebreakers in the Arctic, watch our documentary, Seven Seas of Ice.
Follow: https://t.me/rtdocumentary
🌍 The Canadian Arctic Archipelago includes over 36,000 islands, making it one of the most complex island groups on Earth. These remote lands are mostly uninhabited and covered by ice much of the year. ✨
#islands⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Arctic woolly bear caterpillars survive harsh winters by freezing solid, stopping their heart and body fluids. They produce a natural antifreeze called glycerol to avoid ice damage. Some individuals take up to 14 years to mature into moths through repeated freeze-thaw cycles. ✨
#animals⚡#adaptation⚡#arctic
👉subscribe Interesting Planet
👉more Channels
🌎 In the icy landscapes of Greenland, musk oxen survive Arctic winters thanks to an incredibly dense undercoat called qiviut, which is eight times warmer than sheep’s wool. This soft fiber insulates these shaggy animals so well that snow won't melt on their backs, even in the harshest cold. ✨
#mammals⚡#adaptation⚡#arctic
👉subscribe Interesting Planet
🌎 In 1845, Sir John Franklin led two ships, HMS Erebus and HMS Terror, to chart the Northwest Passage. All 129 crew vanished. Evidence from later searches, including abandoned camps and preserved bodies, showed the crew faced lead poisoning, starvation, and harsh Arctic conditions. The ships’ wrecks were only rediscovered in 2014 and 2016. ✨
#exploration⚡#arctic⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 Lightning rarely strikes the North Pole, but climate change is making Arctic storms more common. Recent years have seen record-breaking lightning outbreaks near the pole’s icy expanse. ✨
#climate⚡#lightning⚡#arctic
👉subscribe Interesting Planet
Трамп вернулся к теме Гренландии
Символично, что и начинался этот и без того насыщенный год с резонансных заявлений американского президента о необходимости присоединения острова к США. И вот на этой неделе Трамп назначил спецпосланника США по Гренландии, тем самым поставив этот вопрос в один ряд с такими внешнеполитическими приоритетами, как Ближний Восток или Украина.
Что касается самого спецпосланника, им стал губернатор Луизианы Джефф Лэндри. Недавно ему исполнилось 55, он имеет степень в области экологических наук и бизнеса, а также степень юриста. Его политическая платформа традиционно консервативна, с акцентом на поддержку энергетической отрасли, особенно нефти и газа. Биография Джеффа Лэндри не связана с Арктическим регионом, да и руководит он южным штатом. Но, как известно, кадровую политику Белого дома сегодня определяет личная преданность Трампу.
За вихрем информационных поводов, которые в этом году генерировал американский президент, могло показаться, что тема присоединения Гренландии плавно сошла на нет. Но нет. После назначения Лэндри поблагодарил Трампа и подтвердил намерение сделать Гренландию частью Соединенных Штатов.
«Речь идет о серьезных планах с американской стороны в отношении Гренландии. Эти планы имеют давние исторические корни. И очевидно, что США будут и дальше на системной основе продвигать свои геостратегические, военно-политические и экономические интересы в Арктике», – говорил нам В.В. Путин на арктическом форуме в Мурманске.
Здесь также хотелось бы отметить, что вся история с Гренландией укладывается в логику новой стратегии национальной безопасности США, предполагающей укрепление позиций Штатов в Западном полушарии.
#Arctic#Greenland#Trump
@semenenkol
🌍 In 2019, a remote underwater mountain range called the Gakkel Ridge was explored beneath Arctic ice. Scientists found hydrothermal vents in this frigid zone, revealing unknown deep-sea ecosystems. ✨
#exploration⚡#ocean⚡#Arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Lena River in Siberia creates the largest natural river delta in the Arctic, spreading into thousands of channels and wetlands that provide vital nesting grounds for millions of migratory birds. ✨
#rivers⚡#wetlands⚡#Arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Svalbard Archipelago, north of mainland Norway, is the northernmost year-round inhabited place on Earth. It’s so remote that polar bears outnumber people here during much of the year. ✨
#archipelago⚡#islands⚡#Arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍