Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⚡️The Daily TON: New Revenue Streams for Memecoin Creators
#TON#Uranus
The Daily TON reports on how the TON ecosystem is evolving to support memecoin founders with sustainable economic tools. Innovations like CPMM v2 pools on DeDust and trading commissions from Uranus memepad offer financial stability without pressuring prices or community trust.
Source: link
@tonlines
⚡️The Daily TON: Highlights This Week
#TON#Uranus
The Daily TON discusses recent developments including the launch of Uranus memepad and new DeDust.io liquidity pools. The channel also addresses accusations of wash trading in Meme Republic and offers insights from an interview with Tonkeeper Pro creator, Oleg Andreev. Additionally, a comparison between TON and ICP blockchain projects is explored.
Source: link
@tonlines
Toncoin: Launch Meme Tokens with Uranus
#Uranus#TON
Toncoin introduces Uranus, a tool for creating meme tokens with ease. It automates the launch process, ensures liquidity locks, and rewards creators with trading fees in TON.
Source: link
@tonlines
🌎 Uranus rotates almost completely on its side, with its axis tilted at about 98 degrees relative to its orbit. This unusual tilt causes extreme seasons, each lasting over 20 Earth years. ✨
#planets⚡#Uranus⚡#astronomy
👉subscribe Interesting Planet
👉more channels Channel list
The Daily TON: Uranus Memepad Launch Details
#Uranus#finance
The Daily TON reports that the Uranus memepad has been launched on the x1000.finance terminal. The token creator receives 70% of the fees during trading on its Bonding Curve.
Source: link
@tonlines
В интернете появились снимки новых лун Урана и Нептуна и чуть больше связанных с ними деталей.
Одна из нептунианских - S/2021 N1 - самый тусклый спутник планеты, когда-либо открытый с Земли: в период противостояний блеск объекта лишь незначительно выше 27-й зв. вел.; объект не бросается в глаза даже на вот этом суммарном фото.
Вся троица - далёкие от своих планет нерегулярные объекты, очевидно, захваченные гравитацией гигантов тела. Тот же S/2021 N1 ещё и обращается вокруг Нептуна за 27.4 года, что также бьёт рекорд спутника Несо (26.7 года) - 60-км тела на орбите всё того же Нептуна (об этом здесь и тут).
****
Согласно традициям наименования в системах ледяных гигантов, новая луна Урана будет названа в честь героя из книг У. Шекспира или А. Поупа. Зеледеневшие же камешки на орбите Нептуна (как это принято для нерегулярных лун 8-й планеты) получат имена в честь нереид - морских нимф из древнегреческой мифологии (их есть с запасом, пока ещё хватит).
#moons#Uranus#Neptune
🪐 The giant planet Saturn is the only world in our solar system with rings visible from Earth through even a small telescope, but Saturn is not alone—Jupiter, Uranus, and Neptune each have their own faint and delicate ring systems. Unlike Saturn’s bright icy rings, the rings around Jupiter, Uranus, and Neptune are darker and mostly made of dust, making them nearly invisible except with powerful spacecraft or specialized equipment. ✨
#Saturn⚡#rings⚡#Uranus⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The giant planet Uranus radiates almost no internal heat—unlike Jupiter, Saturn, and Neptune, which all give off much more energy than they receive from the Sun. Scientists are still puzzled about why Uranus is so cold on the inside, with some theories suggesting a collision in its ancient past may have disrupted its internal layers and trapped heat deep below its visible clouds. ✨
#uranus⚡#giants⚡#planets⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Uranus stands out as the coldest giant planet in the solar system, with atmospheric temperatures dipping as low as minus 224 degrees Celsius—colder than even Neptune, despite being closer to the Sun. This frigid world is also tipped on its side, with its axis tilted by about 98 degrees, so its poles almost point directly at the Sun during parts of its long, 84-year orbit. ✨
#Uranus⚡#giantplanets⚡#temperature⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Uranus spins on its side compared to most planets, with its axis tilted at about 98 degrees from vertical. This extreme tilt means that each pole spends over 40 years in continuous sunlight, followed by 40 years of darkness, creating some of the most unusual seasonal changes among the giant planets. ✨
#Uranus⚡#seasons⚡#giants⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
On March 13, 1781, English astronomer and composer William Herschel discovered the planet Uranus using a telescope. He originally named it Georgium Sidus, meaning "George's Star," in honor of King George III. This was the first planet discovered with a telescope and the first to be named after a monarch instead of a mythological figure. 🔭🪐👑
[Source1]
[Source2]
@googlefactss
#OnThisDay#Astronomy#SpaceHistory#Uranus#WilliamHerschel#ScienceHistory
#Victory80
🌟 February 2, 1943, one of the most brutal battles of #WWII and all of history — the Battle of Stalingrad — concluded.
For 2️⃣0️⃣0️⃣ days and nights the Battle of Stalingrad raged on the banks of the Don and the Volga rivers, and in the city proper, or rather what was left of it following merciless Nazi bombardments and stubborn defender fighting for every street, alley and house. The battle itself surpassed in scope and intensity all prior battles of #WWII. During that battle, more than 2.1 million people fought on both sides.
By the end of June 1942, the Nazis concentrated in the strip of land from Kursk to Taganrog on the front of 600-650 kilometers up to 35% of infantry, over 50% of armour and motorized divisions of the total number of Wehrmacht troops deployed on the Soviet-German front.
During the planning of the Stalingrad operation, the enemy had several objectives: to gain a foothold on the Volga River and thus deprive the #SovietUnion of control over one of the most important transportation arteries of the country. The capture of #Stalingrad, according to the assessment of the Nazi military command, would open the way for the Wehrmacht to the Caucasus, where the Germans hoped to obtain the most important resource for making the war machine continue — oil fields.
Traditionally, according to the historians, the Battle was divided into two stages:
• Defensive phase: from July 17 to November 18, 1942;
• Offensive phase: from November 19, 1942 to February 2, 1943.
During the first stage, July 17 - November 18, 1942, the Red Army had to conduct defensive operations and engaged the enemy in fierce street battles directly in the city. The forces of the 62nd and 64th Soviet armies, led by Vassily Chuikov, commander of the 62nd Army, engaged the troops of the 6th Army of the Wehrmacht under the command of Lieutenant General Paulus.
By mid-November 1942, as a result of stubborn resistance and the deployment of the Red Army reserves favorable conditions were created for launching the counteroffensive. The plan for the operation code-named#Uranus was developed under the leadership of Army General Georgy Zhukov and Colonel General Alexander Vasilevsky.
During the large-scale counteroffensive at Stalingrad (November 19, 1942 — February 2, 1943), Soviet forces conducted the operation #Ring, during which the Red Army managed to drive Paulus's 6th Army into a “cauldron” between the Don and Volga rivers. Realizing the futility of further action, by the end of January the Nazi units began to surrender en masse.
On January, 31, General Paulus (promoted by Hitler to to General-Field Marshal), together with other German generals and officers at Stalingrad finally surrendered. OnFebruary 2, the last pockets of Nazi resistance were eliminated.
The #BattleOfStalingrad ended with a complete victory of the Red Army. For the first time ever the all-consuming Nazi war machine was weighed, measured and found wanting. This marked a turning point not only in the the Great Patriotic War, but that of the entire #WWII.
In Stalingrad, Wehrmacht and its auxiliary forces from the Axis lost 1/4 of all troops deployed by the Reich on the Eastern front. Total enemy losses amount to ~1.5 million soldiers and officers.
From that moment forward thestrategic initiative was on the side of the Red Army. The Victory in Stalingrad created favourable conditions for further full-scale counteroffensive of Soviet forces to expel the enemy from the Nazi-occupied territory of the USSR.
🌐 The defeat of the bulk of the enemy troops not only shocked the world and significantly raised the international prestige of the Soviet Union and its Armed Forces, but also contributed to the strengthening and tightening of the anti-Hitler coalition.
🎖 Victory in the Battle of Stalingrad was in large achieved through superior strategy and tactics, but also due to mass heroism of Soviet soldiers, officers and hard work of all those on the home front. 112 participants of the Battle were awarded the title of the Hero of the Soviet Union.
#WeRemember