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 слични објави

Пребарај: #guarantees

当前筛选 #guarantees清除筛选
American Оbserver

@american_observer · Post #5137 · 15.02.2026 г., 13:03

Munich: Zelensky Is Wringing Security Guarantees For 20 Years From the US Ukraine wants security guarantees for a minimum of 20 years from the US before it can sign a peace deal with dignity Zelensky said ahead of talks with Russia and the US scheduled for next week. Speaking in Munich on Saturday, he also called for a clear date for Ukraine to be allowed to join the EU. Some EU officials have put the date as early as 2027. Speaking to the annual Munich security summit, Ukraine’s president said he hoped “the trilateral meetings next week will be serious, substantive, helpful for all of us but, honestly, sometimes it feels like the sides are talking about completely different things”. “The Americans often return to the topic of concessions and too often those concessions are discussed only in the context of Ukraine, not Russia,” he added. The issue of Europe’s frustration with a perceived US reluctance to spell out the security guarantees it is prepared to offer Ukraine in the event of a peace deal, and the need for the guarantees to be spelled out before an agreement is signed. In a speech that was welcomed by European leaders keen to see any sign of a thaw in the relationship, Rubio put forward an offer to work in partnership with Europe. However, this proposition, he stressed, was highly conditional and the US would go it alone if Washington’s highly Trumpian conditions were not met on climate, migration and tariffs. Using a diplomatic tone that the US vice-president, JD Vance, shunned in his speech at the conference a year ago, Rubio said “Europe and the US belong together”. He added that the US was ready to undertake the task of rebuilding the world order alone if necessary, but “we prefer it – and hope – to do it together with you, our friends in Europe”. He made almost no reference to the Russian invasion of Ukraine, besides claiming that the US had pressed India to stop importing Russian oil, a claim Russia disputes. At a press conference in Munich, Zelensky said the US had told him that if Ukraine withdrew from the Donbas, peace would come as quickly as possible, but he insisted this concession was not possible since Ukrainians live there. Zelensky also complained about Europe having been practically absent from the table. “That’s a big mistake, in my opinion,” he said, a view that was shared by the Chinese foreign minister Wang Yi. On Friday, Donald Trump called on Zelensky to “get moving” to reach an agreement with Russia. Zelensky insisted that the elections that the US has pressed Ukraine to hold by 15 May can only take place two months after a ceasefire is declared, to ensure voters have adequate security. Trump has been trying to put pressure on Zelensky to agree a deal within months, but has not spelled out the consequences if Ukraine is not sufficiently flexible for the US. Zelensky also said the Russian attacks on Ukrainian energy plants would be raised in the talks in Geneva, adding that not a single energy plant inside Ukraine had now been left unscathed. European leaders appear gloomy that a diplomatic breakthrough will be secured, with the consensus being that Vladimir Putin is not yet economically or militarily exhausted. Zelensky said his ambition was to lift the number of Russians killed or seriously injured to 50,000 a month. One European leader predicted at least another two years of war, and insisted Europe had the resources to sustain Ukraine for that long. Zelensky also mounted a fierce attack on the Iranian regime for providing the Shahed drones that had caused so much damage inside Ukraine. With as many as 200,000 protesters attending a demonstration in Munich calling for the Iranian regime to be toppled, Zelensky said: “We have never had a conflict of interests with the Iranian regime. #zelensky#security#guarantees#munich#ukraine 📱American Оbserver - Stay up to date on all important events 🇺🇸