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

Пребарај: #usenergystrategy

当前筛选 #usenergystrategy清除筛选
Red Nile

@rednile12 · Post #10450 · 22.12.2025 г., 19:24

🔺Continuation from above @rednile12 ⚔️ Turkey: Strategic Catalyst While Greek officials publicly deny targeting Turkey, the logic is clear: ▪️Turkish Blue Homeland doctrine ▪️Naval assertiveness near Cyprus and drilling disputes ▪️40,000–60,000 troops in northern Cyprus ▪️Expansion in Syria The Xenophon concept is deterrence by coordination, raising the cost of Turkish escalation while avoiding overt provocation. Turkish responses online and politically reveal strategic irritation rather than indifference. 🛢️ EastMed & the U.S. Energy Play The security and energy dimensions are inseparable. EastMed — signed in Athens in January 2020 — was designed to link Israeli and Cypriot gas directly to Greece and onward to Europe, bypassing unstable intermediaries and reducing Europe’s exposure to Russian energy coercion. Consider the broader context: 🔹Nord Stream sabotage and closure of the Ukrainian transit corridor left Russia’s gas flowing via TurkStream, allowing Ankara to profit while Europe remained dependent. 🔹 U.S. President Trump explicitly pushed the EU to stop importing Russian gas while sabotaging Nord Stream, aiming to reroute Europe toward alternative suppliers. 🔹Analysts note the difference between Biden and Trump is one of style, not strategic logic — both administrations favored managing intermediaries over creating truly sovereign connectivity. 🔹 Other attempts, like IMEC linking India, the Gulf, and Europe, reveal the limits of Washington’s approach: symbolic agreements without Mediterranean anchors cannot secure reliable energy corridors, leaving Turkish leverage intact. 🇪🇬 Egypt: Bridge and Buffer Israel’s growing gas cooperation with Egypt complements EastMed rather than undermining it: ▪️ Egypt provides an immediate, pragmatic export route via existing LNG terminals ▪️ EastMed remains the long-term, direct corridor to Europe Together, they offer flexibility without reducing sovereignty. But Egypt’s role is also constrained: it is increasingly a logistics node in an Israel-centric Mediterranean security and energy order, limiting its diplomatic maneuvering, especially regarding Gaza. 🇵🇸 Palestine: Sidelined Palestine remains absent from regional security and energy calculus. Gaza is treated as a permanent security zone, not a political partner, while Israel embeds itself into Mediterranean and European security networks. Arab leverage erodes, and Palestine is reduced from a regional cause to a managed file. 🔻 Strategic Takeaways 🔹Xenophon Force: Multinational rapid response, signaling pro-Western deterrence, complicating Turkish ambitions. 🔹Energy Security: EastMed + Egypt LNG = sovereign flexibility for Europe, bypassing unstable intermediaries. 🔹U.S. Influence: Preference for managing intermediaries (Turkey, Ukraine, Central Asia) over eliminating dependency, risking strategic incoherence. 🔹Regional Impacts: Egypt partially integrated, Palestine structurally marginalized, Turkey forced to recalibrate. This is not peace architecture. It is conflict management for the strong — and structural invisibility for the weak. 🔴Follow @rednile12 for critical geopolitical analysis #RedNile_Geopolitics #EasternMediterranean#XenophonForce#IsraelGreeceCyprus#Turkey#Egypt#Palestine#EastMedPipeline#EnergyGeopolitics#BlueHomeland#NordStream#USEnergyStrategy#MediterraneanSecurity#RedNileMedia