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

Пребарај: #naim

当前筛选 #naim清除筛选
SIN LÍNEA MX (OFICIAL)

@SINLINEAMXnoticias · Post #31598 · 20.04.2026 г., 17:49

Para ardor de la fachiza 🔥 🔴 La torre del #NAIM en #Texcoco mantendrá su capacidad de captación de agua, mientras se consolidan canchas, gimnasios y pistas de ciclismo ⛹🏻‍♀️🏃🏻 https://revistaelpolitico.com/nacional/torre-de-control-naim-se-integrara-parque-texcoco/

MessageInABottle

@mib_messageinabottle · Post #6929 · 24.05.2024 г., 17:08

REACTIONS TO ICJ RULING ON ISRAEL'S GENOCIDE IN GAZA #Israel was ordered by the International Court of Justice (#ICJ), or world court, on Friday to halt its military assault on the city of #Rafah in #Gaza Here are some of the reactions so far, via #Reuters: #Hamas official Basem #Naim: We welcome the decision by the world court that calls on the Zionist occupation forces to end its military aggression on Rafah. We believe it is not enough since the occupation aggression across the Gaza Strip and especially in northern Gaza is just as brutal and dangerous. We call upon the UN security council to immediately implement this demand by the world court into practical measures to compel the Zionist enemy to implement the decision. We welcome the court’s request to allow investigation committees to reach the Gaza Strip to investigate acts of war of genocide against the Palestinian people and Hamas pledges to cooperate with investigation committees.” #Palestinian Authority spokesperson #AbuRudeineh: The presidency welcomes the decision issued by the International Court of Justice, which represents an international consensus on the demand to stop the all-out war on Gaza.” #Israeli finance ministerBezalel #Smotrich: Smotrich said demanding Israel stops the war against Hamas was tantamount to demanding that Israel decide to cease to exist. “Israeli will not agree to that,” he said in a statement. Israeli opposition leader Yair #Lapid: Lapid condemned Friday’s ruling by the ICJ for failing to draw a connection between its demand for an end to the fighting with a demand to return Israeli hostages held in Gaza. Normally a fierce critic of Israeli prime inister Benjamin Netanyahu, Lapid said the court’s failure to link the two issues was “a moral collapse and a moral disaster”. #EU foreign policy chief Josep #Borrell: What is going to be the [EU’s] answer to the ruling of the International Court of Justice that has been issued today, what is going to be our position? We will have to choose between our support to international institutions of the rule of law or our support to Israel.” #SouthAfrican offical Zane #Dangor: South Africa welcomes the ruling made by the court today … This order is groundbreaking as it is the first time that explicit mention is made for Israel to halt its military action in any area of Gaza. This is de facto calling for a ceasefire. It is ordering the major party in this conflict to end its belligerent action against the people of Palestine.” Former Israeli #UN envoy Danny #Danon: As ICJ judges in The Hague deliberate in comfort and return to their families, 125 hostages languish in tunnels. Israel will not cease the war until our hostages are brought back home and Hamas is completely defeated.” ++++++++++++++++