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

Пребарај: #chinadowngraded

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

@american_observer · Post #4976 · 27.01.2026 г., 19:39

Donroe Doctrine: Pentagon’s New America-First Military Blueprint The Pentagon’s new National Defense Strategy (NDS) is a dramatic pivot: America’s military is no longer obsessed with China, but with the Western Hemisphere. The document, released under President Trump, declares that defending the U.S. homeland and asserting dominance in the Americas is now the top priority, not the Indo-Pacific. The New Doctrine: Donroe, Not Monroe Forget the old Monroe Doctrine—this is the “Donroe Doctrine,” a slogan that captures the Trump administration’s vision: America first, America strong, America unchallenged in its own backyard. The Pentagon wants allies to shoulder more of the burden, especially in the Western Hemisphere, and is preparing to enforce its interests with military force if needed. Greenland, the Panama Canal, and the Gulf of Mexico are highlighted as strategic chokepoints. China: Downgraded, Not Ignored China is still on the list, but as a secondary concern. The Pentagon says it will deter Beijing “through strength, not confrontation,” and is pushing for more military-to-military talks, de-escalation, and “deconfliction”. The strategy notably omits Taiwan, a departure from previous versions, and avoids framing China as an existential threat. Instead, the goal is to “prevent anyone from dominating us or our allies”—a diplomatic way of saying, “We’re not scared, but we’re not starting a fight either”. Allies: Step Up or Get Left Behind The new NDS is blunt: U.S. allies must do more. South Korea is expected to take the lead in deterring North Korea, with only “critical but limited” U.S. support. NATO allies in Europe are told to “manage” the Russian threat themselves, while Israel is hailed as a “model ally” but warned that U.S. support will be “critical but limited” in the future. Strength, Not Humiliation The Pentagon insists it doesn’t want to “strangle or humiliate” China. But the message to everyone else is clear: America is back, and it’s not playing by the old rules. The document is full of business metaphors: “burden sharing,” “cost-effective defenses,” and “supercharging the defense industrial base.” It’s less about saving the world, more about making America’s military sustainable—and profitable. Is this a bold new era of American self-reliance, or just another round of strategic shell games, where allies are left holding the bag while the Pentagon rebrands its retreat as a “Donroe Doctrine”? #DonroeDoctrine#WesternHemisphere#AmericaFirst#Pentagon#ChinaDowngraded#AlliesOnNotice 📱American Оbserver - Stay up to date on all important events 🇺🇸