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

Резултати

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

Пребарај: #baidoa

当前筛选 #baidoa清除筛选
Addis Standard

@addisstandardeng · Post #21889 · 31.03.2026 г., 05:34

News: #Southwest State president resigns after federal forces seize #Baidoa Somalia’s Southwest State President, Abdiaziz Hassan Mohamed Laftagareen announced his resignation on Monday, hours after federal troops and allied armed groups entered Baidoa following clashes that left at least two people dead and 25 others wounded. In a brief statement posted on his official Facebook page, Laftagareen said the resignation was effective immediately, without providing further details. His whereabouts remain unclear. Earlier in the day, forces of the Somali National Armed Forces, backed by allied militias, moved into Baidoa and reportedly took control of key installations, including the police station and major business centers, encountering limited resistance. Regional forces loyal to Laftagareen were said to have withdrawn from parts of the city. According to local reports, strategic sites including the airport and the....... https://x.com/addisstandard/status/2038849050108416203?s=20

Addis Standard

@addisstandardeng · Post #21940 · 04.04.2026 г., 08:19

#Somalian President Mohamud unharmed in mortar attack Somalian President Hassan Sheikh Mohamud was unharmed after he and his entourage were subjected to a barrage of mortar shells in the southern city of #Baidoa on Friday. The shells were fired shortly after the president alighted from his plane and began greeting army units, police and government officials said. https://www.bloomberg.com/news/articles/2026-04-04/somalian-president-mohamud-unharmed-in-mortar-attack

Addis Standard

@addisstandardeng · Post #21911 · 02.04.2026 г., 05:16

#Somali forces reopen key Mogadishu–Baidoa route as defense minister signals intensified offensive Minister of Defense of the Federal Government of Somalia, Ahmed Moalim Fiqi, has announced that government forces have fully secured the strategic road linking #Mogadishu and #Baidoa, a major breakthrough in ongoing military operations. In an interview with national television, the Minister said the Somali National Army successfully cleared and reopened the route earlier this week after swiftly dislodging militant fighters from key positions. “The road is now safe for civilian movement, restoring vital connectivity between the capital and the Bay region”, He said. He stated that the armed forces have regained strong operational capacity and are now able to conduct precise offensives in remaining militant-held areas. Recent operations include preemptive strikes and a surprise attack on.... https://www.facebook.com/AddisstandardEng/posts/pfbid02MvxWBnGmjHxoqi12Tii5cZDWqSXj1gLp14Nf3vXPFcpnhRKdMiLn6ho3nLc3pPNul

Addis Standard

@addisstandardeng · Post #21886 · 30.03.2026 г., 15:27

News: #Somali Federal forces seize key installations in #Baidoa as political tensions between #Mogadishu, #Southwest_State escalate Somali National Armed Forces (SNAF), accompanied by allied militias, took control of the town’s police station, major business centers, and key installations after entering Baidoa without major clashes. Earlier on Monday, President Abdiaziz Hassan Mohamed warned against federal military intervention in the region. “Any attack on Baidoa or South West State territory will be met with an appropriately severe military response,” he said in a statement posted on his official X account on March 30. “I urge President Hassan Sheikh to use the remainder of his short time in office to not spill Somali blood but help find a solution for a credible election process.” https://addisstandard.com/?p=56188

Addis Standard

@addisstandardeng · Post #21754 · 18.03.2026 г., 05:28

Federal government suspends #Mogadishu–#Baidoa flights after Southwest halts cooperation #Somalia’s federal government on Tuesday suspended civilian flights between Mogadishu and Baidoa, in a move widely seen as increasing pressure on #Southwest State authorities amid a deepening political standoff. Local sources said that as of Tuesday morning, commercial passenger aircrafts were unable to land in Baidoa following the decision. Only #United_Nations and cargo flights were being permitted to operate during the suspension. Officials in Southwest State condemned the measure. “The Somali government has stopped passenger planes from arriving in Baidoa. People entered the airport at 6:00 this morning, and they have not been allowed to departure yet,” said Ilyas Ali Nur, a senior official in the regional administration. Sources indicated that flight clearances had been..... https://www.hiiraan.com/news4/2026/Mar/204688/federal_government_suspends_mogadishubaidoa_flights_after_southwest_halts_cooperation.aspx