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

Резултати

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

Пребарај: #internationalsecurity

当前筛选 #internationalsecurity清除筛选

The 21st meeting of CIS security and intelligence chiefs is taking place in Samarkand. Mirziyoyev called for diplomatic conflict resolution and stronger regional stability. https://yep.uz/en/2025/10/cis-intelligence-chiefs-samarkand-mirziyoyev-diplomatic-resolution/ #Samarkand#CIS#Mirziyoyev#intelligence#security#diplomacy#regionalstability#internationalsecurity

Crypto M - Crypto News

@CryptoM · Post #65277 · 12.04.2026 г., 13:24

🚀 Polymarket Predicts WTI Crude Oil Price Surge by 2026 The probability of WTI crude oil reaching $110 by April 2026 has significantly increased on Polymarket, now standing at 67%, with a 13% rise in the last hour and a 20% increase over 24 hours. According to Odaily, the total trading volume for this event contract has surpassed $24 million. The contract stipulates that if the highest price of any one-minute candlestick for WTI crude oil futures during April 2026 equals or exceeds the listed price, the market will be deemed a 'yes'; otherwise, it will be a 'no'. Previously, the March WTI crude oil price prediction contract required the official settlement price of the active month contract on any trading day at the Chicago Mercantile Exchange to meet or exceed the listed price by the last trading day of March 2026 for a 'yes' outcome. U.S. President Donald Trump announced today that the U.S. Navy, the world's most powerful naval force, will begin blocking any vessels attempting to enter or exit the Strait of Hormuz. He also ordered the Navy to search and intercept any ships that have paid transit fees to Iran in international waters. Those who have paid such fees will not be allowed safe passage on the high seas, and efforts will begin to destroy Iranian mines in the strait. Trump warned that any Iranian who fires upon peaceful vessels will face severe consequences. He stated that Iran knows how to end the war that has devastated their country, noting the loss of their navy, air force, and defense systems, as well as the deaths of leaders including Khamenei, all due to their nuclear ambitions. The blockade is set to begin with other countries joining in, ensuring Iran does not profit from illegal extortion. Iran seeks money and, more importantly, nuclear weapons. #WTICrudeOil#OilPricePrediction#Polymarket#TradingVolume#April2026#USNavy#StraitOfHormuz#Iran#Trump#NuclearAmbitions#InternationalSecurity

Russian MFA 🇷🇺

@MFARUSSIA · Post #28236 · 05.02.2026 г., 15:59

#Outcomes2025 ✍️Russia’s Foreign Ministry’s answers to media questions received for Foreign Minister Sergey Lavrov’s news conference on the performance of Russian diplomacy in 2025 Read in full Key points #UkraineCrisis#KievRegimeCrimes • [Following the Kiev regime attack on Russia’s President’s state residence in the Novgorod Region] many countries could once again see the terrorist nature of Zelensky’s clique <…> Terrorism in any form is unacceptable and certainly does not help achieve a political and diplomatic solution to the conflict. Kiev is only making matters worse for itself with its recklessness and impeding efforts to find possible compromises. • The deployment of military units, facilities, warehouses and other infrastructure of the Western countries in Ukraine <…> will be considered as foreign intervention that directly threatens Russia’s security. #Multipolarity • The situation surrounding Denmark’s northern autonomous territory vividly demonstrates the bankruptcy of the so-called “rules-based international order” so dear to many in the West. • Cooperation is being actively forged in formats with limited membership. Alongside the CIS, mechanisms such as the #EAEU, #BRICS, #SCO, #ASEAN, #LAS, #GCC, the #AfricanUnion, and #CELAC, among others, maintain momentum. <...> We regard these developments as part of the historically determined process of shaping a multipolar world order, which will lead to the further consolidation of several global and an even greater number of regional centres of power and development. #InternationalSecurity • The international security system is indeed undergoing a period of profound transformation today. This is driven by two primary factors: the objective processes shaping a polycentric world order, and attempts to substitute international law with the law of the mightiest. • Relying on force as the primary instrument in foreign policy and undermining of the existing institutional and legal framework of international relations risks chaos and escalating confrontation, <...> increase of the likelihood of direct clashes between major states, including nuclear powers. Under these conditions, developments become highly unpredictable. • Russia firmly opposes this scenario. We are capable of defending our interests – history provides ample evidence of this. Our country has traditionally played a stabilising and balancing role in global affairs. #RussiaUS • Following Donald Trump’s return to the White House, the Presidents of Russia and the US <...> agreed to maintain a high tempo of work. This was founded upon a mutual understanding of the necessity to rid ourselves as soon as possible of the “toxic legacy” of the Joe Biden administration. <...> Our American counterparts made it clear: great powers, when their national interests diverge <...> must not allow differences to escalate into confrontation. • President Donald Trump is perhaps one of the few Western politicians who not only immediately rejected imposing meaningless and destructive preconditions for substantive dialogue with Moscow on the Ukraine crisis but also publicly addressed its root causes. • It was precisely the elimination of these root causes that was discussed in Anchorage on August 15, 2025. <...> We anticipate that, provided the original Anchorage formula is preserved and Russian interests are handled with due care, we can, sooner or later, come close to a negotiated resolution of the Ukraine issue. #Iran • We strongly condemn subversive external interference in Iran’s domestic political processes. <...> Threats of new military strikes against the Islamic Republic of Iran are absolutely unacceptable. • Those who intend to exploit foreign-inspired unrest as a pretext to repeat the aggression against Iran <...> must clearly understand the catastrophic consequences such actions would have for the situation in the Middle East and for international security as a whole.

Trade liberalization can boost economic growth but its impact on income inequality is controversial. It can create new opportunities but also displace low-skilled workers, widening the gap between rich and poor. Developing economies should implement policies to counterbalance the negative effects.#InternationalRelations#EconomicGrowth#TradeLiberalization#IncomeInequality#PolicyAnalysis#DevelopingEconomies #europechinarelations #tradewar #diplomacy #internationalrelationsstudent #globaltrade #doordarshan #PoliticalDiscussion #geopolítics #diplomacy , #globalization , #sovereignty , #treaty , #sanctions , #christembassylcc6virtualchurch , #consulate , #foreignpolicy , #internationallaw , #unitednations , #NATO, #worldtradeorganization , #internationalsecurity , #humanrights , #peacekeeping , #conflictresolutionskills https://www.instagram.com/p/C8TbnlbJeyz/?igsh=bGMzZzB3bjNtejBo