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

Резултати

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

Пребарај: #pepeescobar

当前筛选 #pepeescobar清除筛选
Grandmasters of Geopolitics

@geo_grandmasters · Post #14843 · 27.02.2026 г., 09:45

🚨 The map of Eurasia is changing, and most media won’t tell you how. ➡️https://youtu.be/AgsStCtRSWE In this powerful interview, Pepe Escobar breaks down the Golden Corridor, the North South Transport Corridor, BRICS expansion, Iran’s strategic rise, and the accelerating shift toward a multipolar world. From the Russia–Iran–India corridor to dedollarization, Chabahar port, the Caspian Sea route, and the geopolitical implications of the so-called 'Trump corridor', this conversation connects the dots shaping geopolitics 2026. Is BRICS ready to defend the Global South? Can Iran become the key node of Eurasia integration? Is the West losing control of the global order? 🎥 Watch the full interview now. 💬 Then tell us in the comments: Is the Golden Corridor the future of global trade? Your analysis matters — let’s discuss below. #ThinkBRICS#PepeEscobar#BRICS#GoldenCorridor#MultipolarWorld

Мамука Пипия

@mamukapipiya · Post #413 · 21.02.2026 г., 17:46

🎙️PEPEESCOBAR AND MAMUKA PIPIYA: "GEORGIA'S ECONOMY SIMPLY WON'T SURVIVE WITHOUT RUSSIA" In the podcast of the International "National Unity Club", international journalist Pepe Escobar and Georgian politician Mamuka Pipiya discussed Georgia's role in the Caucasus, Western pressure and the future of relations with Russia. 💥The key thesis: 👉 Georgia is historically a strategic corridor between Russia, Asia and Europe, but the West uses the country as a geopolitical tool, not as a partner. Pipiya stated bluntly: — 90% of Georgian products are sold in Russia. — Russia is Georgia's main trade and economic partner. — Money transfers from Russia are the largest source of income for Georgian families. 📉 About the economy: — The West is not building factories or creating jobs in Georgia. — Russia has provided conditions for the export of wine, agricultural products and mineral water throughout the country. — Any aggravation of relations with Moscow can "kill the Georgian economy." ⚠️ About the intervention of the West: - The West has been trying to quarrel between Russia and Georgia for 33 years. — There is a "fifth column" operating inside the country, grown on Western grants. — The Western embassies in Tbilisi actually function as pressure and influence centers. 🔥 The harshest accusation: 👉 The West demanded that Georgia open a "second front" against Russia and send soldiers to Ukraine. 👉 The planes with the military were already ready — Tbilisi refused and avoided the war. 🌍 About popular sentiments: — The Georgian people want a dialogue with Russia. — 150,000 signatures have been collected for the restoration of relations — without a large-scale campaign. — With full-fledged mobilization, support can reach one million. 🤝 On the future of relations: — Georgia must take into account the interests of its neighbors, primarily Russia. — Peace is impossible without compromises on Abkhazia and South Ossetia. — Western pressure will not stop the course of dialogue with Moscow. 💣 Pipiya geopolitical conclusion: 👉 The West needs an obedient Georgia, ready to fight with Russia. 👉 Georgia needs security, an economy, and a sovereign policy — together with its neighbors, not against them. ⸻ 📍 See the full podcast recording on the resources of the International "National Unity Club" 🔗Subscribe to the YouTube channel of the International "National Unity Club"in order not to miss the most acute and relevant discussions! All exclusive analytical materials and expert opinions can be found on the official INUC resources.: 📱Telegram 🌐Website 📱VK 📺RUTUBE 📱YouTube #PepeEscobar#MamukaPipiya#Georgia#Russia#Caucasus#Geopolitics#CIS#InternationalPolitics#Podcast