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

Пребарај: #axisjapan

当前筛选 #axisjapan清除筛选

🎙 Briefing by Russia's Foreign Ministry Spokeswoman Maria Zakharova (Moscow, November 14, 2025) 🔹#KievRegimeCrimes 🔹Ukraine crisis 🔹Moldovan government’s decision to denounce seven CIS agreements 🔹Developments in El Fasher, Sudan 🔹The US counter-narcotics policy in Latin America 🔹Anti-Russian conference in Dublin 🔹G7 Foreign Ministers’ Meeting in Canada 📰Read 📺Watch #KievRegimeCrimes The neo-Nazi regime in Kiev continues to terrorise civilians in Russia. Over the past week, 53 Russian citizens suffered from artillery shelling and drone strikes, with 8 people killed and 45 injured, including six children. Russian courts continue to hand down sentences to Ukrainian neo-Nazis and mercenaries. In absentia, mercenaries from Georgia, Colombia, and the Czech Republic who participated in combat on the side of the Ukrainian Armed Forces have been sentenced to 28, 13.5, and 13 years in prison. #Ireland#EU#Militarisation Militaristic rhetoric of the [Brussels bureaucracy] finds fertile ground in Dublin, where the ruling coalition <…> is pursuing a course to revise constitutional restrictions on the participation of Irish service members in overseas missions. The Irish run the risk of becoming pawns in reckless geopolitical games of the Westerners (Anglo-Saxons), who are clearly acting against Russia, with all the negative consequences for [Ireland] that this entails. #US#LatinAmerica Since September 2025, we have been witnessing an unprecedented military campaign launched by Washington in Latin America under the pretext of allegedly combating drug-trafficking routes into the United States. We are extremely concerned by the military methods chosen by the United States to address this issue, which amount to little more than blatant interference in the internal affairs of Latin American states. We firmly oppose the use of force or the threat of force to interfere in internal affairs under various pretexts, including counter-narcotics operations. #AxisJapan#WarCrimes#NoStatuteOfLimitations We continue our work on disclosing information about the crimes of Japanese militarism. We have repeatedly emphasised that these crimes have no statute of limitations. Procedural actions aimed at bringing all those responsible to justice continue to this day. Between March and June, the Prosecutor General’s Office of the Russian Federation adopted decisions annulling the conclusions issued in the 1980s–2000s that had granted rehabilitation to 24 Japanese citizens. Following the review of court rulings in cassation and supervisory instances, it was established that these individuals are not subject to rehabilitation. Their guilt has been fully proven. #US#Tariffs From an economic standpoint, the introduction of 500% tariffs on goods from third countries that purchase Russian oil and gas seems absurd. This is tantamount to the discontinuation of all trade relations between countries, as such a tariff rate is prohibitive. Russian energy resources are supplied to dozens of states around the world, including Europe, the Asia-Pacific region, China, and India. It is downright impossible to substitute such volumes of oil and natural gas on the global market within reasonable timeframes. Those who call for [such measures] are likely unaware of the negative consequences this would have both for the United States itself and for the global economy as a whole. Moreover, such a step would be a gross violation of international trade law.