TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 133 слични објави

Пребарај: #sudan

当前筛选 #sudan清除筛选
White House Watch

@WhiteHouseWatch · Post #18049 · 09.03.2026 г., 18:49

#Sudan: Il Segretario di Stato Marco Rubio ha annunciato con un post su X che la branca sudanese di Fratellanza Musulmana è stata designata come "organizzazione terroristica estera" e "organizzazione terroristica particolarmente designata" dal Dipartimento di Stato americano, in quanto supportata ed addestrata dalle IRGC iraniane.

Hashtags

The Pakistan News — پاکستان 🇵🇰

@thepakistannews · Post #14313 · 31.03.2026 г., 21:58

— 🇸🇩: Last week the UAE backed RSF militia kidnapped a girl from the Nahda neighbourhood of Nyala and forcibly detained her for five days. During this time, the victim was subjected to the most horrific forms of torture and gang rape, before being thrown onto a public road in a critical physical and psychological state. #Sudan @NewsfromSudan

Hashtags

POPULAR FRONT

@popularxfront · Post #5671 · 30.03.2026 г., 18:25

🇸🇩#Sudan: Two families (reportedly nine people) were killed after an artillery shell fired by the Rapid Support Forces (RSF) struck a residential neighborhood in the city of Dilling, South Kordofan State, yesterday. On March 28th, a partial blockade was reported in the area due to renewed clashes between the Sudanese Armed Forces and the RSF. The army was reportedly successful in repelling an attempted RSF advance. The rebels are attempting to re-establish control in the Kordofan area after the army broke an almost two-year-long siege in early January. (via @SudanTribune_EN on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #5054 · 20.02.2026 г., 09:50

🇸🇩#Sudan: Three aid workers were killed and four others were injured in a drone strike by the Rapid Support Forces (RSF) on an aid convoy in South Kordofan yesterday. The convoy, which was carrying food and other supplies, was hit while passing through the Kartala area. This would be the second strike on an aid convoy this month by the RSF. (via Al Jazeera)

Hashtags

POPULAR FRONT

@popularxfront · Post #4874 · 02.02.2026 г., 15:13

🇸🇩#Sudan: Sudanese Armed Forces have launched an offensive against Rapid Support Forces toward the Al-Rahad - Um Ruwaba axis in North Kordofan, capturing the Al-Uba area from RSF militants. Meanwhile, several drone strikes against RSF positions were also reported in Zalingei, western Sudan. (📹 via @Sudan_tweet on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #4869 · 01.02.2026 г., 19:58

🇸🇩#Sudan: Aerial footage shows a drone operated by the Sudanese Armed Forces (SAF) dropping an explosive payload next to two trucks carrying Rapid Support Forces (RSF) militants. (via @war_noir)

Hashtags

POPULAR FRONT

@popularxfront · Post #4832 · 31.01.2026 г., 10:27

🇸🇩#Sudan: Sudanese Armed Forces (SAF) have shot down three RSF kamikaze drones which were allegedly attempting to target civilian infrastructure in the city of Al-Ubayyid, North Kordofan State.

Hashtags

POPULAR FRONT

@popularxfront · Post #4820 · 30.01.2026 г., 11:37

🇸🇩#Sudan: Intense clashes continue between the Sudanese Armed Forces (SAF) and remnants of the Rapid Support Forces (RSF). Footage shows SAF Special Mission Forces (SMF) charging toward remaining RSF militants on the outskirts of South Kordofan, following weeks of heavy fighting in Dilling, where the RSF was recently pushed out. (📹 via @Sudanis0 on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #4766 · 27.01.2026 г., 16:32

🇸🇩#Sudan: The Sudanese Armed Forces have reportedly broken through RSF lines and lifted the siege on the city of Dilling in South Kordofan after nearly two and a half years of blockade. The army says it reopened the Dilling road following intense clashes with RSF militants, claiming heavy losses were inflicted on the militia in both personnel and equipment. The RSF group has maintained a siege on Dilling since January 2024. (via @AfriMEOSINT & @Sudan_tweet on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #4725 · 25.01.2026 г., 11:21

🇸🇩#Sudan: Rapid Support Forces (RSF) have recently shot down a SAF (Sudanese Armed Forces) drone. The drone was a Baykar Bayraktar TB2, which is supplied by Turkey. (via @war_noir)

Hashtags

POPULAR FRONT

@popularxfront · Post #4101 · 09.12.2025 г., 11:09

🇸🇩#Sudan: Videos show Rapid Support Forces (RSF) militants inside the Heglig oil fields and the SAF's 90th Brigade headquarters after taking full control of the area in West Kordofan, including the town and its oil infrastructure. Before the Sudanese Armed Forces pulled out, an official report states that operators in the area had already shut down their facilities and evacuated personnel to Unity State in South Sudan. Meanwhile, the oil field had been inactive since August, when a drone strike prompted authorities to suspend all work at the site. (via Al Jazeera; 📹 via @AFRIMEOSINT on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #4013 · 29.11.2025 г., 19:21

🇸🇩#Sudan: Sudanese Armed Forces have shelled multiple Rapid Support Forces (RSF) positions across several axes in Kordofan. Reports also indicate Sudanese drone strikes earlier today in Al-Fula and Geneina in West Kordofan. In the footage, a reconnaissance drone can be seen coming down near the soldiers. (Via @Sudan_tweet on X)

Hashtags

123•••101112
ПретходнаСтраница 1 од 12Следна