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

Резултати

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

Пребарај: #conflict

当前筛选 #conflict清除筛选
Trump's Ear

@trumpsear_tg · Post #2341 · 06.04.2026 г., 15:59

The United States is depleting its tungsten reserves, a resource critical to the military-industrial complex, according to Foreign Policy. 🔗 Tungsten is essential for manufacturing armor-piercing ammunition, missile components, and aviation equipment. Currently, the United States does not commercially produce tungsten and relies heavily on imports, primarily from China, which dominates the global market. 🌍 Since the escalation of conflict in the Middle East, tungsten prices have surged by over 500%. 📈 Expanding production remains challenging due to limited industrial capacity. Sources indicate that the United States is already confronting a tungsten shortage with no immediate resolution in sight. Even prior to the conflict, the Pentagon sought to reduce its dependence on tungsten, though the extent of their success remains uncertain. ⚙️🇺🇸 #conflict 👂More on Trump's Ear ⚠️

Hashtags

Borkena

@borkena · Post #5185 · 03.11.2025 г., 03:48

The Impact of War and Conflict on Ethiopia’s Rising Poverty: Explaining the World Bank’s 43% Poverty Projection under Abiy Ahmed’s Administration. Read more. https://borkena.com/2025/11/02/impact-of-war-and-conflict-on-ethiopias-rising-poverty-explaining-the-world-banks-43-poverty-projection-under-abiy-ahmeds-administration#Ethiopia#Conflict

Borkena

@borkena · Post #5657 · 30.12.2025 г., 19:43

The Partitioned State: How Internal Failures and External Interventions Shattered Sudan. Read. https://borkena.com/2025/12/30/sudan-the-partitioned-state-how-internal-failures-and-external-interventions-shattered-sudan/#Sudan#Conflict

Borkena

@borkena · Post #5468 · 06.12.2025 г., 03:56

Will Ethiopia End Up Like Sudan? A Comparative Analysis of Two African Conflicts. Read more. https://borkena.com/2025/12/05/will-ethiopia-end-up-like-sudan-a-comparative-analysis-of-two-african-conflicts/#Ethiopia#Sudan#conflict

Addis Standard

@addisstandardeng · Post #21470 · 20.02.2026 г., 12:12

News: Risk of renewed #conflict mounts as troop movements reported near #Eritrea–#Tigray border—Bloomberg Addis Abeba—Ethiopia and Eritrea are deploying troops and military equipment near the northern Tigray region, raising the risk of renewed conflict in the Horn of Africa, Bloomberg reported, citing regional diplomats. Sources familiar with the matter told Bloomberg that Ethiopian troops and equipment have been moved northward, including through Bahir Dar, while Eritrean forces have also deployed to areas inside Tigray. Prime Minister Abiy Ahmed this week reiterated Ethiopia’s longstanding ambition to secure access to the Red Sea, describing maritime access as key to overcoming logistical constraints on economic growth. Eritrean state television also broadcast a naval parade in Massawa last week, marking the anniversary of the city’s capture in 1990. https://addisstandard.com/?p=55268

BadVolf

@badvolfnews · Post #1110 · 09.10.2023 г., 07:25

📢 Breaking News 📢 Israel's fight against Hamas is taking longer than expected. Battles are raging in multiple locations outside Gaza. Armed militants infiltrated the kibbutz Beeri, some still hiding. Situation remains unstable. Stay tuned for updates. #Israel#Hamas#Conflict https://www.gazeta.ru/army/news/2023/10/09/21458629.shtml Subscribe to @BadVolfNews

Eurasia & Multipolarity

@EurasianChoice · Post #61859 · 02.05.2026 г., 17:40

🇮🇱 Israel demolishes Catholic school in Lebanon — reports spark outrage ​ Israeli forces reportedly used bulldozers to demolish a Catholic monastery and school in the Lebanese border town of Yaroun, according to Anadolu Ajansı. ​ Local residents and clergy have condemned the действия as a war crime, while Israel is said to justify operations as part of creating a “buffer zone” in southern Lebanon. ​ ➡The incident has drawn criticism over the lack of response from Western governments. ​ #Israel#Lebanon#MiddleEast#Conflict#Religion ​ 🔘Subscribe now!Chat

ПретходнаСтраница 1 од 4Следна