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

Резултати

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

Пребарај: #gazastrip

当前筛选 #gazastrip清除筛选
Marwa Osman/MidEaStream

@Marwa_OsmanLB · Post #3977 · 06.02.2025 г., 14:56

In an unprecedented move following his shock proposal for the permanent resettlement of the more than two million Palestinians from Gaza to neighboring countries, President Donald Trump announced a controversial plan for the U.S. to take over the Gaza Strip. This statement, made during a press conference with Israeli PM Benjamin Netanyahu, raised eyebrows worldwide. A journalist cornered Trump so he sought Bibi’s help to complete his answer. #UnitedStates#Israel#DonaldTrump#BenjaminNetanyahu#GazaStrip

Embassy of Russia in Singapore

@rusembsg · Post #4288 · 18.10.2025 г., 04:54

🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025) 💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump. The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange. Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world. Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region. A special emphasis during the conversation was placed on the #UkraineCrisis. ❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods. In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly. *** Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts. It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation. Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop. The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement. In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance. On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse. Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact. 🇷🇺🇺🇸#RussiaUS

Россия в ОБСЕ

@RusMissionOSCE · Post #7506 · 16.10.2025 г., 22:36

🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025) 💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump. The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange. Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world. Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region. A special emphasis during the conversation was placed on the #UkraineCrisis. ❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods. In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly. *** Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts. It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation. Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop. The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement. In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance. On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse. Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact. 🇷🇺🇺🇸#RussiaUS

Russian Embassy in Cambodia

@russian_embassy_in_cambodia · Post #5317 · 17.10.2025 г., 02:09

🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025) 💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump. The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange. Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world. Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region. A special emphasis during the conversation was placed on the #UkraineCrisis. ❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods. In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly. *** Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts. It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation. Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop. The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement. In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance. On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse. Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact. 🇷🇺🇺🇸#RussiaUS

🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025) 💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump. The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange. Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world. Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region. A special emphasis during the conversation was placed on the #UkraineCrisis. ❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods. In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly. *** Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts. It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation. Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop. The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement. In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance. On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse. Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact. 🇷🇺🇺🇸#RussiaUS