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

Резултати

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

Пребарај: #russialas

当前筛选 #russialas清除筛选
Russian MFA 🇷🇺

@MFARUSSIA · Post #28436 · 18.02.2026 г., 19:29

🎙 Russia's Foreign Minister Sergey Lavrov’sinterview with Al Arabiya television channel(Moscow, February 17, 2026) Key talking points: #TheArabWorld • We enjoy solid relationships with all Arab countries and their organisations. These include the League of Arab States (LAS), with which we have held about half a dozen ministerial meetings. We also plan to hold the Russia-LAS summit. We also maintain a close relationship with the Gulf Cooperation Council (GCC), which has been maintained by annual events at the level of foreign ministers. #SaudiArabia • Saudi Arabia is the leader of the Arab world, a country of two Holiest sites in Islam, and the author of the Arab Peace Initiative to settle the most complicated and enduring crisis, the Palestinian issue. • Our country regards Saudi Arabia as its strategic partner in the region. We believe that this view is shared by our Saudi colleagues. We are very pleased with our cooperation. • We are developing humanitarian, cultural, educational and sports ties. <...> A few days ago, I had a conversation with my friend, Foreign Minister Faisal bin Farhan Al Saud. One of the issues we discussed concerned the preparation of Intervision International Music Contest, which reflects the striving of Russia and Saudi Arabia to promote traditional values. • We enjoy solid relationships with all Arab countries and their organisations. These include the #LAS, with which we have held about half a dozen ministerial meetings. We also plan to hold the #RussiaLAS summit. We also maintain a close relationship with #GCC. #Iran • Regrettably, Israel and the US went ahead with the strikes [against Iran], creating physical risks and undermining the authority of the #IAEA and the #NPT. The IAEA has exerted unprecedented control, especially in the past years, after the signing of the #JCPOA. Iran was never found violating the Non-Proliferation Treaty or its agreement on guarantees with the IAEA. All risks and political tensions emerged after the US withdrew from the JCPOA in 2018. #Syria • Mutual respect and mutual benefit – these are the principles that have underpinned our relations with Syria from the very beginning, since its establishment. We hold these relations in high regard. • We firmly believe that a multiethnic, multi-confessional state such as Syria must restore its unity, territorial integrity, and sovereignty as swiftly as possible. In this endeavour, we will continue to – and indeed already do – assist Damascus and its new leadership. • As for our military facilities, discussions are ongoing. Let me reiterate: the Syrians are keen for our presence to endure. #Palestine • We should not overlook the fact that the situation in the West Bank is becoming increasingly tense and volatile as a result of Israeli actions, including the recent issuance of directives regulating land acquisition and urban development procedures. Until recently, such matters were coordinated with the Palestinian National Authority. Now, however, unilateral decisions are being taken, and analysis of their likely consequences suggests that little may remain of the territories currently administered by the Palestinian National Authority. Now, however, unilateral decisions are being taken, and analysis of their likely consequences suggests that little may remain of the territories currently administered by the Palestinian National Authority. #UkrainianCrisis • Europe hysterically demands that Russia start talks and that all sides agree that Europe must be part of these talks. <...> Europe has revealed its Nazi essence, which we thought was destroyed with the Hitler’s defeat in WWII. It has turned out to be extremely tenacious. I don’t see what role Europe could play. • We greatly value the stance taken by the Trump administration and personally by the President of the US. We are closely observing Europe’s attempts to dissuade the current Washington administration from its principled stance, as discussed and agreed in Anchorage, Alaska. We remain fully committed to those understandings. Read in full